code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/env python
import unittest
from flickrapi import shorturl
class ShortUrlTest(unittest.TestCase):
'''Tests the shorturl module.'''
def test_encoding(self):
'''Test ID to Base58 encoding.'''
self.assertEqual(shorturl.encode(u'4325695128'), u'7Afjsu')
self.assertEqual(shorturl.encode(u'2811466321'), u'5hruZg')
def test_decoding(self):
'''Test Base58 to ID decoding.'''
self.assertEqual(shorturl.decode(u'7Afjsu'), u'4325695128')
self.assertEqual(shorturl.decode(u'5hruZg'), u'2811466321')
def test_short_url(self):
'''Test photo ID to short URL conversion.'''
self.assertEqual(shorturl.url(u'4325695128'),
u'http://flic.kr/p/7Afjsu')
self.assertEqual(shorturl.url(u'2811466321'),
u'http://flic.kr/p/5hruZg')
| Python |
# -*- coding: utf-8 -*-
import doctest
import glob
import os
import os.path
import sys
import unittest
import flickrapi
failure = False
def exit(statuscode):
'''Replacement for sys.exit that records the status code instead of
exiting.
'''
global failure
if statuscode:
failure = True
def run_in_module_dir(module):
'''Runs the decorated function in the directory of the given module.'''
directory = os.path.dirname(module.__file__)
def decorator(func):
'''Runs the decorated function in some directory.'''
def wrapper():
curdir = os.getcwd()
try:
if directory:
print 'Changing to %s' % directory
os.chdir(directory)
return func()
finally:
os.chdir(curdir)
return wrapper
return decorator
run_in_test_dir = run_in_module_dir(sys.modules[__name__])
run_in_code_dir = run_in_module_dir(flickrapi)
def load_module(modulename):
'''load_module(modulename) -> module'''
__import__(modulename)
return sys.modules[modulename]
@run_in_test_dir
def run_unittests():
'''Runs all unittests in the current directory.'''
filenames = glob.glob('test_*.py')
modules = [fn[:-3] for fn in filenames]
for modulename in modules:
module = load_module('%s.%s' % (__name__, modulename))
print '----------------------------------------------------------------------'
print module.__file__
print
unittest.main(module=module)
if failure:
print 'Unittests: there was at least one failure'
else:
print 'Unittests: All tests ran OK'
@run_in_code_dir
def run_doctests():
'''Runs all doctests in the flickrapi module.'''
# First run the flickrapi module
(failure_count, test_count) = doctest.testmod(flickrapi)
# run the submodules too.
filenames = glob.glob('[a-z]*.py')
modules = [fn[:-3] for fn in filenames]
# Go to the top-level source directory to ensure relative path names are
# correct.
os.chdir('..')
for modulename in modules:
# Load the module
module = load_module('%s.%s' % (flickrapi.__name__, modulename))
# Run the tests
(failed, tested) = doctest.testmod(module)
failure_count += failed
test_count += tested
if failure_count:
print 'Doctests: %i of %i failed' % (failure_count, test_count)
global failure
failure = True
else:
print 'Doctests: all of %i OK' % test_count
def run_tests():
'''Runs all unittests and doctests.'''
# Prevent unittest.main from calling sys.exit()
orig_exit = sys.exit
sys.exit = exit
try:
run_unittests()
run_doctests()
finally:
sys.exit = orig_exit
sys.exit(failure)
if __name__ == '__main__':
run_tests()
| Python |
import urllib
import cStringIO
import Image
def get_static_google_map(filename_wo_extension, center=None, zoom=None, imgsize="500x500", imgformat="jpeg",
maptype="roadmap", markers=None ):
"""retrieve a map (image) from the static google maps server
See: http://code.google.com/apis/maps/documentation/staticmaps/
Creates a request string with a URL like this:
http://maps.google.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=14&size=512x512&maptype=roadmap
&markers=color:blue|label:S|40.702147,-74.015794&sensor=false"""
# assemble the URL
request = "http://maps.google.com/maps/api/staticmap?" # base URL, append query params, separated by &
# if center and zoom are not given, the map will show all marker locations
if center != None:
request += "center=%s&" % center
#request += "center=%s&" % "40.714728, -73.998672" # latitude and longitude (up to 6-digits)
#request += "center=%s&" % "50011" # could also be a zipcode,
#request += "center=%s&" % "Brooklyn+Bridge,New+York,NY" # or a search term
if center != None:
request += "zoom=%i&" % zoom # zoom 0 (all of the world scale ) to 22 (single buildings scale)
request += "size=%ix%i&" % (imgsize) # tuple of ints, up to 640 by 640
request += "format=%s&" % imgformat
request += "maptype=%s&" % maptype # roadmap, satellite, hybrid, terrain
# add markers (location and style)
if markers != None:
for marker in markers:
request += "%s&" % marker
#request += "mobile=false&" # optional: mobile=true will assume the image is shown on a small screen (mobile device)
request += "sensor=false&" # must be given, deals with getting loction from mobile device
print request
urllib.urlretrieve(request, filename_wo_extension+"."+imgformat) # Option 1: save image directly to disk
# Option 2: read into PIL
web_sock = urllib.urlopen(request)
imgdata = cStringIO.StringIO(web_sock.read()) # constructs a StringIO holding the image
try:
PIL_img = Image.open(imgdata)
# if this cannot be read as image that, it's probably an error from the server,
except IOError:
print "IOError:", imgdata.read() # print error (or it may return a image showing the error"
# show image
#else:
#PIL_img.show()
#PIL_img.save(filename_wo_extension+".png", "PNG") # save as jpeg
if __name__ == '__main__':
# make a map around a center
get_static_google_map("amsterdam", center="52.38,4.9", zoom=12, imgsize=(800,800),
imgformat="png", maptype="satellite" )
| Python |
#!/usr/bin/env python
'''Python distutils install script.
Run with "python setup.py install" to install FlickrAPI
'''
import distribute_setup
distribute_setup.use_setuptools()
import sys
# Check the Python version
(major, minor) = sys.version_info[:2]
if (major, minor) < (2, 4):
raise SystemExit("Sorry, Python 2.4 or newer required")
import _setup
| Python |
#!python
"""Bootstrap distribute installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from distribute_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools, set a download
mirror, or use an alternate download directory, you can do so by supplying
the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools.
"""
import os
import sys
import time
import fnmatch
import tempfile
import tarfile
from distutils import log
try:
from site import USER_SITE
except ImportError:
USER_SITE = None
try:
import subprocess
def _python_cmd(*args):
args = (sys.executable,) + args
return subprocess.call(args) == 0
except ImportError:
# will be used for python 2.3
def _python_cmd(*args):
args = (sys.executable,) + args
# quoting arguments if windows
if sys.platform == 'win32':
def quote(arg):
if ' ' in arg:
return '"%s"' % arg
return arg
args = [quote(arg) for arg in args]
return os.spawnl(os.P_WAIT, sys.executable, *args) == 0
DEFAULT_VERSION = "0.6.8"
DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/"
SETUPTOOLS_PKG_INFO = """\
Metadata-Version: 1.0
Name: setuptools
Version: 0.6c9
Summary: xxxx
Home-page: xxx
Author: xxx
Author-email: xxx
License: xxx
Description: xxx
"""
def _install(tarball):
# extracting the tarball
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
tar = tarfile.open(tarball)
_extractall(tar)
tar.close()
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
# installing
log.warn('Installing Distribute')
assert _python_cmd('setup.py', 'install')
finally:
os.chdir(old_wd)
def _build_egg(egg, tarball, to_dir):
# extracting the tarball
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
tar = tarfile.open(tarball)
_extractall(tar)
tar.close()
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
# building an egg
log.warn('Building a Distribute egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
finally:
os.chdir(old_wd)
# returning the result
log.warn(egg)
if not os.path.exists(egg):
raise IOError('Could not build the egg.')
def _do_download(version, download_base, to_dir, download_delay):
egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg'
% (version, sys.version_info[0], sys.version_info[1]))
if not os.path.exists(egg):
tarball = download_setuptools(version, download_base,
to_dir, download_delay)
_build_egg(egg, tarball, to_dir)
sys.path.insert(0, egg)
import setuptools
setuptools.bootstrap_install_from = egg
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, download_delay=15, no_fake=True):
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
was_imported = 'pkg_resources' in sys.modules or \
'setuptools' in sys.modules
try:
try:
import pkg_resources
if not hasattr(pkg_resources, '_distribute'):
if not no_fake:
_fake_setuptools()
raise ImportError
except ImportError:
return _do_download(version, download_base, to_dir, download_delay)
try:
pkg_resources.require("distribute>="+version)
return
except pkg_resources.VersionConflict:
e = sys.exc_info()[1]
if was_imported:
sys.stderr.write(
"The required version of distribute (>=%s) is not available,\n"
"and can't be installed while this script is running. Please\n"
"install a more recent version first, using\n"
"'easy_install -U distribute'."
"\n\n(Currently using %r)\n" % (version, e.args[0]))
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return _do_download(version, download_base, to_dir,
download_delay)
except pkg_resources.DistributionNotFound:
return _do_download(version, download_base, to_dir,
download_delay)
finally:
if not no_fake:
_create_fake_setuptools_pkg_info(to_dir)
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15):
"""Download distribute from a specified location and return its filename
`version` should be a valid distribute version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download
attempt.
"""
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
tgz_name = "distribute-%s.tar.gz" % version
url = download_base + tgz_name
saveto = os.path.join(to_dir, tgz_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
log.warn("Downloading %s", url)
src = urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = src.read()
dst = open(saveto, "wb")
dst.write(data)
finally:
if src:
src.close()
if dst:
dst.close()
return os.path.realpath(saveto)
def _patch_file(path, content):
"""Will backup the file then patch it"""
existing_content = open(path).read()
if existing_content == content:
# already patched
log.warn('Already patched.')
return False
log.warn('Patching...')
_rename_path(path)
f = open(path, 'w')
try:
f.write(content)
finally:
f.close()
return True
def _same_content(path, content):
return open(path).read() == content
def _rename_path(path):
new_name = path + '.OLD.%s' % time.time()
log.warn('Renaming %s into %s', path, new_name)
try:
from setuptools.sandbox import DirectorySandbox
def _violation(*args):
pass
DirectorySandbox._violation = _violation
except ImportError:
pass
os.rename(path, new_name)
return new_name
def _remove_flat_installation(placeholder):
if not os.path.isdir(placeholder):
log.warn('Unkown installation at %s', placeholder)
return False
found = False
for file in os.listdir(placeholder):
if fnmatch.fnmatch(file, 'setuptools*.egg-info'):
found = True
break
if not found:
log.warn('Could not locate setuptools*.egg-info')
return
log.warn('Removing elements out of the way...')
pkg_info = os.path.join(placeholder, file)
if os.path.isdir(pkg_info):
patched = _patch_egg_dir(pkg_info)
else:
patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO)
if not patched:
log.warn('%s already patched.', pkg_info)
return False
# now let's move the files out of the way
for element in ('setuptools', 'pkg_resources.py', 'site.py'):
element = os.path.join(placeholder, element)
if os.path.exists(element):
_rename_path(element)
else:
log.warn('Could not find the %s element of the '
'Setuptools distribution', element)
return True
def _after_install(dist):
log.warn('After install bootstrap.')
placeholder = dist.get_command_obj('install').install_purelib
_create_fake_setuptools_pkg_info(placeholder)
def _create_fake_setuptools_pkg_info(placeholder):
if not placeholder or not os.path.exists(placeholder):
log.warn('Could not find the install location')
return
pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1])
setuptools_file = 'setuptools-0.6c9-py%s.egg-info' % pyver
pkg_info = os.path.join(placeholder, setuptools_file)
if os.path.exists(pkg_info):
log.warn('%s already exists', pkg_info)
return
log.warn('Creating %s', pkg_info)
f = open(pkg_info, 'w')
try:
f.write(SETUPTOOLS_PKG_INFO)
finally:
f.close()
pth_file = os.path.join(placeholder, 'setuptools.pth')
log.warn('Creating %s', pth_file)
f = open(pth_file, 'w')
try:
f.write(os.path.join(os.curdir, setuptools_file))
finally:
f.close()
def _patch_egg_dir(path):
# let's check if it's already patched
pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
if os.path.exists(pkg_info):
if _same_content(pkg_info, SETUPTOOLS_PKG_INFO):
log.warn('%s already patched.', pkg_info)
return False
_rename_path(path)
os.mkdir(path)
os.mkdir(os.path.join(path, 'EGG-INFO'))
pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
f = open(pkg_info, 'w')
try:
f.write(SETUPTOOLS_PKG_INFO)
finally:
f.close()
return True
def _before_install():
log.warn('Before install bootstrap.')
_fake_setuptools()
def _under_prefix(location):
if 'install' not in sys.argv:
return True
args = sys.argv[sys.argv.index('install')+1:]
for index, arg in enumerate(args):
for option in ('--root', '--prefix'):
if arg.startswith('%s=' % option):
top_dir = arg.split('root=')[-1]
return location.startswith(top_dir)
elif arg == option:
if len(args) > index:
top_dir = args[index+1]
return location.startswith(top_dir)
elif option == '--user' and USER_SITE is not None:
return location.startswith(USER_SITE)
return True
def _fake_setuptools():
log.warn('Scanning installed packages')
try:
import pkg_resources
except ImportError:
# we're cool
log.warn('Setuptools or Distribute does not seem to be installed.')
return
ws = pkg_resources.working_set
try:
setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools',
replacement=False))
except TypeError:
# old distribute API
setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools'))
if setuptools_dist is None:
log.warn('No setuptools distribution found')
return
# detecting if it was already faked
setuptools_location = setuptools_dist.location
log.warn('Setuptools installation detected at %s', setuptools_location)
# if --root or --preix was provided, and if
# setuptools is not located in them, we don't patch it
if not _under_prefix(setuptools_location):
log.warn('Not patching, --root or --prefix is installing Distribute'
' in another location')
return
# let's see if its an egg
if not setuptools_location.endswith('.egg'):
log.warn('Non-egg installation')
res = _remove_flat_installation(setuptools_location)
if not res:
return
else:
log.warn('Egg installation')
pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO')
if (os.path.exists(pkg_info) and
_same_content(pkg_info, SETUPTOOLS_PKG_INFO)):
log.warn('Already patched.')
return
log.warn('Patching...')
# let's create a fake egg replacing setuptools one
res = _patch_egg_dir(setuptools_location)
if not res:
return
log.warn('Patched done.')
_relaunch()
def _relaunch():
log.warn('Relaunching...')
# we have to relaunch the process
args = [sys.executable] + sys.argv
sys.exit(subprocess.call(args))
def _extractall(self, path=".", members=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers().
"""
import copy
import operator
from tarfile import ExtractError
directories = []
if members is None:
members = self
for tarinfo in members:
if tarinfo.isdir():
# Extract directories with a safe mode.
directories.append(tarinfo)
tarinfo = copy.copy(tarinfo)
tarinfo.mode = 448 # decimal for oct 0700
self.extract(tarinfo, path)
# Reverse sort directories.
if sys.version_info < (2, 4):
def sorter(dir1, dir2):
return cmp(dir1.name, dir2.name)
directories.sort(sorter)
directories.reverse()
else:
directories.sort(key=operator.attrgetter('name'), reverse=True)
# Set correct owner, mtime and filemode on directories.
for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except ExtractError:
e = sys.exc_info()[1]
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e)
def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
tarball = download_setuptools()
_install(tarball)
if __name__ == '__main__':
main(sys.argv[1:])
| Python |
#!/usr/bin/env python
import tests
tests.run_tests()
| Python |
from pythonmap import *
get_static_google_map("amsterdam", center="52.38,4.9", zoom=12, imgsize=(800,800), imgformat="png", maptype="satellite" )
| Python |
# adjust cwd and sys.path
def adjust_to_correct_appdir():
import os, sys
try:
appdir = __file__
print appdir
if not appdir:
raise ValueError
appdir = os.path.abspath(os.path.dirname(__file__))
os.chdir(appdir)
sys.path = [ e for e in sys.path if e != appdir]
sys.path.insert(0,os.path.join(appdir, 'libs'))
sys.path.insert(0,os.path.join(appdir, 'game_src'))
except ValueError:
print 'Please run from an OS console.'
import time
time.sleep(10)
sys.exit(1)
adjust_to_correct_appdir()
# handle options
def get_options():
import optparse
parser = optparse.OptionParser()
parser.add_option("-x", "--width", type='int', dest="width", default='800',
help="set window width", metavar="WIDTH")
parser.add_option("-y", "--height", type="int", dest="height", default='600',
help="set window height", metavar="HEIGHT")
parser.add_option("-F", "--fullscreen", dest="fullscreen", default=False,
help="set fullscreen mode on", action="store_true")
parser.add_option("--startlevel", type='int', dest="startlevel", default='-1',
help="first level to play", metavar="STARTLEVEL")
parser.add_option("--sound", dest="sound", default=True,
help="enables sound, default True", metavar="sound")
(options, args) = parser.parse_args()
members = ['width', 'height', 'fullscreen', 'startlevel', 'sound']
d = {}
for k in members:
d[k] = getattr(options, k)
return d
import gg
gg.session = get_options()
#print options
# todo get audio potential availability
import main
main.run_game()
| Python |
# kytten/button.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import pyglet
from widgets import Control
from override import KyttenLabel
class Button(Control):
"""
A simple text-labeled button.
"""
def __init__(self, text="", id=None, on_click=None, disabled=False):
"""
Creates a new Button. The provided text will be used to caption the
button.
@param text Label for the button
@param on_click Callback for the button
@param disabled True if the button should be disabled
"""
Control.__init__(self, id=id, disabled=disabled)
self.text = text
self.on_click = on_click
self.label = None
self.button = None
self.highlight = None
self.is_pressed = False
def delete(self):
"""
Clean up our graphic elements
"""
Control.delete(self)
if self.button is not None:
self.button.delete()
self.button = None
if self.label is not None:
self.label.delete()
self.label = None
if self.highlight is not None:
self.highlight.delete()
self.highlight = None
def layout(self, x, y):
"""
Places the Button.
@param x X coordinate of lower left corner
@param y Y coordinate of lower left corner
"""
Control.layout(self, x, y)
self.button.update(self.x, self.y, self.width, self.height)
if self.highlight is not None:
self.highlight.update(self.x, self.y, self.width, self.height)
x, y, width, height = self.button.get_content_region()
font = self.label.document.get_font()
self.label.x = x + width/2 - self.label.content_width/2
self.label.y = y + height/2 - font.ascent/2 - font.descent
def on_gain_highlight(self):
Control.on_gain_highlight(self)
self.size(self.saved_dialog)
if self.highlight is not None:
self.highlight.update(self.x, self.y, self.width, self.height)
def on_lose_highlight(self):
Control.on_lose_highlight(self)
if self.highlight is not None:
self.highlight.delete()
self.highlight = None
def on_mouse_press(self, x, y, button, modifiers):
if not self.is_pressed and not self.is_disabled():
self.is_pressed = True
# Delete the button to force it to be redrawn
self.delete()
self.saved_dialog.set_needs_layout()
def on_mouse_release(self, x, y, button, modifiers):
if self.is_pressed:
self.is_pressed = False
# Delete the button to force it to be redrawn
self.delete()
self.saved_dialog.set_needs_layout()
# Now, if mouse is still inside us, signal on_click
if self.on_click is not None and self.hit_test(x, y):
if self.id is not None:
self.on_click(self.id)
else:
self.on_click()
def size(self, dialog):
"""
Sizes the Button. If necessary, creates the graphic elements.
@param dialog Dialog which contains the Button
"""
if dialog is None:
return
Control.size(self, dialog)
if self.is_pressed:
path = ['button', 'down']
else:
path = ['button', 'up']
if self.is_disabled():
color = dialog.theme[path]['disabled_color']
else:
color = dialog.theme[path]['gui_color']
if self.button is None:
self.button = dialog.theme[path]['image'].generate(
color,
dialog.batch, dialog.bg_group)
if self.highlight is None and self.is_highlight():
self.highlight = dialog.theme[path]['highlight']['image'].\
generate(dialog.theme[path]['highlight_color'],
dialog.batch,
dialog.bg_group)
if self.label is None:
self.label = KyttenLabel(self.text,
font_name=dialog.theme[path]['font'],
font_size=dialog.theme[path]['font_size'],
color=dialog.theme[path]['text_color'],
batch=dialog.batch, group=dialog.fg_group)
# Treat the height of the label as ascent + descent
font = self.label.document.get_font()
height = font.ascent - font.descent # descent is negative
self.width, self.height = self.button.get_needed_size(
self.label.content_width, height)
def teardown(self):
self.on_click = None
Control.teardown(self) | Python |
# kytten/theme.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import os
import pyglet
from pyglet import gl
try:
import json
json_load = json.loads
except ImportError:
try:
import simplejson as json
json_load = json.loads
except ImportError:
import sys
print >>sys.stderr, \
"Warning: using 'safe_eval' to process json files, " \
"please upgrade to Python 2.6 or install simplejson"
import safe_eval
def json_load(expr):
# strip carriage returns
return safe_eval.safe_eval(''.join(str(expr).split('\r')))
DEFAULT_THEME_SETTINGS = {
"font": "Lucida Grande",
"font_size": 12,
"font_size_small": 10,
"text_color": [255, 255, 255, 255],
"gui_color": [255, 255, 255, 255],
"highlight_color": [255, 255, 255, 64],
"disabled_color": [160, 160, 160, 255],
}
class ThemeTextureGroup(pyglet.graphics.TextureGroup):
"""
ThemeTextureGroup, in addition to setting the texture, also ensures that
we map to the nearest texel instead of trying to interpolate from nearby
texels. This prevents 'blooming' along the edges.
"""
def set_state(self):
pyglet.graphics.TextureGroup.set_state(self)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
gl.GL_NEAREST)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER,
gl.GL_NEAREST)
class UndefinedGraphicElementTemplate:
def __init__(self, theme):
self.theme = theme
self.width = 0
self.height = 0
self.margins = [0, 0, 0, 0]
self.padding = [0, 0, 0, 0]
def generate(self, color, batch, group):
return UndefinedGraphicElement(self.theme, color, batch, group)
def write(self, f, indent=0):
f.write('None')
class TextureGraphicElementTemplate(UndefinedGraphicElementTemplate):
def __init__(self, theme, texture, width=None, height=None):
UndefinedGraphicElementTemplate.__init__(self, theme)
self.texture = texture
self.width = width or texture.width
self.height = height or texture.height
def generate(self, color, batch, group):
return TextureGraphicElement(self.theme, self.texture,
color, batch, group)
def write(self, f, indent=0):
f.write('{\n')
f.write(' ' * (indent + 2) + '"src": "%s"' % self.texture.src)
if hasattr(self.texture, 'region'):
f.write(',\n' + ' ' * (indent + 2) + '"region": %s' %
repr(list(self.texture.region)))
f.write('\n' + ' ' * indent + '}')
class FrameTextureGraphicElementTemplate(TextureGraphicElementTemplate):
def __init__(self, theme, texture, stretch, padding,
width=None, height=None):
TextureGraphicElementTemplate.__init__(self, theme, texture,
width=width, height=height)
self.stretch_texture = texture.get_region(*stretch).get_texture()
x, y, width, height = stretch
self.margins = (x, texture.width - width - x, # left, right
texture.height - height - y, y) # top, bottom
self.padding = padding
def generate(self, color, batch, group):
return FrameTextureGraphicElement(
self.theme, self.texture, self.stretch_texture,
self.margins, self.padding, color, batch, group)
def write(self, f, indent=0):
f.write('{\n')
f.write(' ' * (indent + 2) + '"src": "%s"' % self.texture.src)
if hasattr(self.texture, 'region'):
f.write(',\n' + ' ' * (indent + 2) + '"region": %s' %
repr(list(self.texture.region)))
left, right, top, bottom = self.margins
if left != 0 or right != 0 or top != 0 or bottom != 0 or \
self.padding != [0, 0, 0, 0]:
stretch = [left, bottom,
self.width - right - left, self.height - top - bottom]
f.write(',\n' + ' ' * (indent + 2) + '"stretch": %s' %
repr(list(stretch)))
f.write(',\n' + ' ' * (indent + 2) + '"padding": %s' %
repr(list(self.padding)))
f.write('\n' + ' ' * indent + '}')
class TextureGraphicElement:
def __init__(self, theme, texture, color, batch, group):
self.x = self.y = 0
self.width, self.height = texture.width, texture.height
self.group = ThemeTextureGroup(texture, group)
self.vertex_list = batch.add(4, gl.GL_QUADS, self.group,
('v2i', self._get_vertices()),
('c4B', color * 4),
('t3f', texture.tex_coords))
def _get_vertices(self):
x1, y1 = int(self.x), int(self.y)
x2, y2 = x1 + int(self.width), y1 + int(self.height)
return (x1, y1, x2, y1, x2, y2, x1, y2)
def delete(self):
self.vertex_list.delete()
self.vertex_list = None
self.group = None
def get_content_region(self):
return (self.x, self.y, self.width, self.height)
def get_content_size(self, width, height):
return width, height
def get_needed_size(self, content_width, content_height):
return content_width, content_height
def update(self, x, y, width, height):
self.x, self.y, self.width, self.height = x, y, width, height
if self.vertex_list is not None:
self.vertex_list.vertices = self._get_vertices()
class FrameTextureGraphicElement:
def __init__(self, theme, texture, inner_texture, margins, padding,
color, batch, group):
self.x = self.y = 0
self.width, self.height = texture.width, texture.height
self.group = ThemeTextureGroup(texture, group)
self.outer_texture = texture
self.inner_texture = inner_texture
self.margins = margins
self.padding = padding
self.vertex_list = batch.add(36, gl.GL_QUADS, self.group,
('v2i', self._get_vertices()),
('c4B', color * 36),
('t2f', self._get_tex_coords()))
def _get_tex_coords(self):
x1, y1 = self.outer_texture.tex_coords[0:2] # outer's lower left
x4, y4 = self.outer_texture.tex_coords[6:8] # outer's upper right
x2, y2 = self.inner_texture.tex_coords[0:2] # inner's lower left
x3, y3 = self.inner_texture.tex_coords[6:8] # inner's upper right
return (x1, y1, x2, y1, x2, y2, x1, y2, # bottom left
x2, y1, x3, y1, x3, y2, x2, y2, # bottom
x3, y1, x4, y1, x4, y2, x3, y2, # bottom right
x1, y2, x2, y2, x2, y3, x1, y3, # left
x2, y2, x3, y2, x3, y3, x2, y3, # center
x3, y2, x4, y2, x4, y3, x3, y3, # right
x1, y3, x2, y3, x2, y4, x1, y4, # top left
x2, y3, x3, y3, x3, y4, x2, y4, # top
x3, y3, x4, y3, x4, y4, x3, y4) # top right
def _get_vertices(self):
left, right, top, bottom = self.margins
x1, y1 = int(self.x), int(self.y)
x2, y2 = x1 + int(left), y1 + int(bottom)
x3 = x1 + int(self.width) - int(right)
y3 = y1 + int(self.height) - int(top)
x4, y4 = x1 + int(self.width), y1 + int(self.height)
return (x1, y1, x2, y1, x2, y2, x1, y2, # bottom left
x2, y1, x3, y1, x3, y2, x2, y2, # bottom
x3, y1, x4, y1, x4, y2, x3, y2, # bottom right
x1, y2, x2, y2, x2, y3, x1, y3, # left
x2, y2, x3, y2, x3, y3, x2, y3, # center
x3, y2, x4, y2, x4, y3, x3, y3, # right
x1, y3, x2, y3, x2, y4, x1, y4, # top left
x2, y3, x3, y3, x3, y4, x2, y4, # top
x3, y3, x4, y3, x4, y4, x3, y4) # top right
def get_content_region(self):
left, right, top, bottom = self.padding
return (self.x + left, self.y + bottom,
self.width - left - right, self.height - top - bottom)
def get_content_size(self, width, height):
left, right, top, bottom = self.padding
return width - left - right, height - top - bottom
def get_needed_size(self, content_width, content_height):
left, right, top, bottom = self.padding
return (max(content_width + left + right, self.outer_texture.width),
max(content_height + top + bottom, self.outer_texture.height))
def delete(self):
self.vertex_list.delete()
self.vertex_list = None
self.group = None
def update(self, x, y, width, height):
self.x, self.y, self.width, self.height = x, y, width, height
if self.vertex_list is not None:
self.vertex_list.vertices = self._get_vertices()
class UndefinedGraphicElement(TextureGraphicElement):
def __init__(self, theme, color, batch, group):
self.x = self.y = self.width = self.height = 0
self.group = group
self.vertex_list = batch.add(12, gl.GL_LINES, self.group,
('v2i', self._get_vertices()),
('c4B', color * 12))
def _get_vertices(self):
x1, y1 = int(self.x), int(self.y)
x2, y2 = x1 + int(self.width), y1 + int(self.height)
return (x1, y1, x2, y1, x2, y1, x2, y2,
x2, y2, x1, y2, x1, y2, x1, y1,
x1, y1, x2, y2, x1, y2, x2, y1)
class ScopedDict(dict):
"""
ScopedDicts differ in several useful ways from normal dictionaries.
First, they are 'scoped' - if a key exists in a parent ScopedDict but
not in the child ScopedDict, we return the parent value when asked for it.
Second, we can use paths for keys, so we could do this:
path = ['button', 'down', 'highlight']
color = theme[path]['highlight_color']
This would return the highlight color assigned to the highlight a button
should have when it is clicked.
"""
def __init__(self, arg={}, parent=None):
self.parent = parent
for k, v in arg.iteritems():
if isinstance(v, dict):
self[k] = ScopedDict(v, self)
else:
self[k] = v
def __getitem__(self, key):
if key is None:
return self
elif isinstance(key, list) or isinstance(key, tuple):
if len(key) > 1:
return self.__getitem__(key[0]).__getitem__(key[1:])
elif len(key) == 1:
return self.__getitem__(key[0])
else:
return self # theme[][key] should return theme[key]
else:
try:
return dict.__getitem__(self, key)
except KeyError:
if self.parent is not None:
return self.parent.__getitem__(key)
else:
raise
def __setitem__(self, key, value):
if isinstance(value, dict):
dict.__setitem__(self, key, ScopedDict(value, self))
else:
dict.__setitem__(self, key, value)
def get(self, key, default=None):
if isinstance(key, list) or isinstance(key, tuple):
if len(key) > 1:
return self.__getitem__(key[0]).get(key[1:], default)
elif len(key) == 1:
return self.get(key[0], default)
else:
raise KeyError(key) # empty list
if self.has_key(key):
return dict.get(self, key)
elif self.parent:
return self.parent.get(key, default)
else:
return default
def get_path(self, path, default=None):
assert isinstance(path, list) or isinstance(path, tuple)
if len(path) == 1:
return self.get(path[0], default)
else:
return self.__getitem__(path[0]).get_path(path[1:], default)
def set_path(self, path, value):
assert isinstance(path, list) or isinstance(path, tuple)
if len(path) == 1:
return self.__setitem__(path[0], value)
else:
return self.__getitem__(path[0]).set_path(path[1:], value)
def write(self, f, indent=0):
f.write('{\n')
first = True
for k, v in self.iteritems():
if not first:
f.write(',\n')
else:
first = False
f.write(' ' * (indent + 2) + '"%s": ' % k)
if isinstance(v, ScopedDict):
v.write(f, indent + 2)
elif isinstance(v, UndefinedGraphicElementTemplate):
v.write(f, indent + 2)
elif isinstance(v, basestring):
f.write('"%s"' % v)
elif isinstance(v, tuple):
f.write('%s' % repr(list(v)))
else:
f.write(repr(v))
f.write('\n')
f.write(' ' * indent + '}')
class Theme(ScopedDict):
"""
Theme is a dictionary-based class that converts any elements beginning
with 'image' into a GraphicElementTemplate. This allows us to specify
both simple textures and 9-patch textures, and more complex elements.
"""
def __init__(self, arg, override={}, default=DEFAULT_THEME_SETTINGS,
allow_empty_theme=False, name='theme.json'):
"""
Creates a new Theme.
@param arg The initializer for Theme. May be:
* another Theme - we'll use the same graphic library but
apply an override for its dictionary.
* a dictionary - interpret any subdirectories where the key
begins with 'image' as a GraphicElementTemplate
* a filename - read the JSON file as a dictionary
@param override Replace some dictionary entries with these
@param default Initial dictionary entries before handling input
@param allow_empty_theme True if we should allow creating a new theme
"""
ScopedDict.__init__(self, default, None)
self.groups = {}
if isinstance(arg, Theme):
self.textures = arg.textures
for k, v in arg.iteritems():
self.__setitem__(k, v)
self.update(override)
return
if isinstance(arg, dict):
self.loader = pyglet.resource.Loader(os.getcwd())
input = arg
else:
if os.path.isfile(arg) or os.path.isdir(arg):
self.loader = pyglet.resource.Loader(path=arg)
try:
theme_file = self.loader.file(name)
input = json_load(theme_file.read())
theme_file.close()
except pyglet.resource.ResourceNotFoundException:
input = {}
else:
input = {}
self.textures = {}
self._update_with_images(self, input)
self.update(override)
def __getitem__(self, key):
try:
return ScopedDict.__getitem__(self, key)
except KeyError, e:
if key.startswith('image'):
return UndefinedGraphicElementTemplate(self)
else:
raise e
def _get_texture(self, filename):
"""
Returns the texture associated with a filename. Loads it from
resources if we haven't previously fetched it.
@param filename The filename of the texture
"""
if not self.textures.has_key(filename):
texture = self.loader.texture(filename)
texture.src = filename
self.textures[filename] = texture
return self.textures[filename]
def _get_texture_region(self, filename, x, y, width, height):
"""
Returns a texture region.
@param filename The filename of the texture
@param x X coordinate of lower left corner of region
@param y Y coordinate of lower left corner of region
@param width Width of region
@param height Height of region
"""
texture = self._get_texture(filename)
retval = texture.get_region(x, y, width, height).get_texture()
retval.src = texture.src
retval.region = [x, y, width, height]
return retval
def _update_with_images(self, target, input):
"""
Update a ScopedDict with the input dictionary. Translate
images into texture templates.
@param target The ScopedDict which is to be populated
@param input The input dictionary
"""
for k, v in input.iteritems():
if k.startswith('image'):
if isinstance(v, dict):
width = height = None
if v.has_key('region'):
x, y, width, height = v['region']
texture = self._get_texture_region(
v['src'], x, y, width, height)
else:
texture = self._get_texture(v['src'])
if v.has_key('stretch'):
target[k] = FrameTextureGraphicElementTemplate(
self,
texture,
v['stretch'],
v.get('padding', [0, 0, 0, 0]),
width=width, height=height)
else:
target[k] = TextureGraphicElementTemplate(
self, texture, width=width, height=height)
else:
target[k] = TextureGraphicElementTemplate(
self, self._get_texture(v))
elif isinstance(v, dict):
temp = ScopedDict(parent=target)
self._update_with_images(temp, v)
target[k] = temp
else:
target[k] = v
def write(self, f, indent=0):
ScopedDict.write(self, f, indent)
f.write('\n')
| Python |
# kytten/dialog.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import pyglet
from pyglet import gl
from widgets import Widget, Control, Label
from button import Button
from frame import Wrapper, Frame
from layout import GetRelativePoint, ANCHOR_CENTER
from layout import VerticalLayout, HorizontalLayout
class DialogEventManager(Control):
def __init__(self):
"""
Creates a new event manager for a dialog.
@param content The Widget which we wrap
"""
Control.__init__(self)
self.controls = []
self.control_areas = {}
self.control_map = {}
self.hover = None
self.focus = None
self.wheel_hint = None
self.wheel_target = None
def get_value(self, id):
widget = self.get_widget(id)
if widget is not None:
return widget.get_value()
def get_values(self):
retval = {}
for widget in self.controls:
if widget.is_input() and widget.id is not None:
retval[widget.id] = widget.get_value()
return retval
def get_widget(self, id):
return self.control_map.get(id)
def hit_control(self, x, y, control):
left, right, top, bottom = self.control_areas[control]
if x >= left and x < right and y >= bottom and y < top:
return control.hit_test(x, y)
else:
return False
def on_key_press(self, symbol, modifiers):
"""
TAB and ENTER will move us between fields, holding shift will
reverse the direction of our iteration. We don't handle ESCAPE.
Otherwise, we pass keys to our child elements.
@param symbol Key pressed
@param modifiers Modifiers for key press
"""
if symbol in [pyglet.window.key.TAB, pyglet.window.key.ENTER]:
focusable = [x for x in self.controls
if x.is_focusable() and not x.is_disabled()]
if not focusable:
return
if modifiers & pyglet.window.key.MOD_SHIFT:
dir = -1
else:
dir = 1
if self.focus is not None and self.focus in focusable:
index = focusable.index(self.focus)
else:
index = 0 - dir
new_focus = focusable[(index + dir) % len(focusable)]
self.set_focus(new_focus)
new_focus.ensure_visible()
# If we hit ENTER, and wrapped back to the first focusable,
# pass the ENTER back so the Dialog can call its on_enter callback
if symbol != pyglet.window.key.ENTER or \
new_focus != focusable[0]:
return pyglet.event.EVENT_HANDLED
elif symbol != pyglet.window.key.ESCAPE:
if self.focus is not None and hasattr(self.focus, 'on_key_press'):
return self.focus.on_key_press(symbol, modifiers)
def on_key_release(self, symbol, modifiers):
"""Pass key release events to the focus
@param symbol Key released
@param modifiers Modifiers for key released
"""
if self.focus is not None and hasattr(self.focus, 'on_key_release'):
return self.focus.on_key_release(symbol, modifiers)
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
"""
Handles mouse dragging. If we have a focus, pass it in.
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param dx Delta X
@param dy Delta Y
@param buttons Buttons held while moving
@param modifiers Modifiers to apply to buttons
"""
if self.focus is not None:
self.focus.dispatch_event('on_mouse_drag',
x, y, dx, dy, buttons, modifiers)
return pyglet.event.EVENT_HANDLED
def on_mouse_motion(self, x, y, dx, dy):
"""
Handles mouse motion. We highlight controls that we are hovering
over.
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param dx Delta X
@param dy Delta Y
"""
if self.hover is not None and self.hit_control(x, y, self.hover):
self.hover.dispatch_event('on_mouse_motion', x, y, dx, dy)
new_hover = None
for control in self.controls:
if self.hit_control(x, y, control):
new_hover = control
break
self.set_hover(new_hover)
if self.hover is not None:
self.hover.dispatch_event('on_mouse_motion', x, y, dx, dy)
def on_mouse_press(self, x, y, button, modifiers):
"""
If the focus is set, and the target lies within the focus, pass the
message down. Otherwise, check if we need to assign a new focus.
If the mouse was pressed within our frame but no control was targeted,
we may be setting up to drag the Dialog around.
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param button Button pressed
@param modifiers Modifiers to apply to button
"""
if self.focus is not None and self.hit_control(x, y, self.focus):
self.focus.dispatch_event('on_mouse_press',
x, y, button, modifiers)
return pyglet.event.EVENT_HANDLED
else:
if self.hit_test(x, y):
self.set_focus(self.hover)
if self.focus is not None:
self.focus.dispatch_event('on_mouse_press',
x, y, button, modifiers)
return pyglet.event.EVENT_HANDLED
else:
self.set_focus(None)
def on_mouse_release(self, x, y, button, modifiers):
"""
Button was released. We pass this along to the focus, then we
generate an on_mouse_motion to handle changing the highlighted
Control if necessary.
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param button Button released
@param modifiers Modifiers to apply to button
"""
self.is_dragging = False
if self.focus is not None:
self.focus.dispatch_event('on_mouse_release',
x, y, button, modifiers)
DialogEventManager.on_mouse_motion(self, x, y, 0, 0)
return pyglet.event.EVENT_HANDLED
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
"""
Mousewheel was scrolled. See if we have a wheel target, or
failing that, a wheel hint.
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param scroll_x Number of clicks horizontally mouse was moved
@param scroll_y Number of clicks vertically mouse was moved
"""
if self.wheel_target is not None and \
self.wheel_target in self.controls:
self.wheel_target.dispatch_event('on_mouse_scroll',
x, y, scroll_x, scroll_y)
return pyglet.event.EVENT_HANDLED
elif self.wheel_hint is not None and \
self.wheel_hint in self.controls:
self.wheel_hint.dispatch_event('on_mouse_scroll',
x, y, scroll_x, scroll_y)
return pyglet.event.EVENT_HANDLED
def on_text(self, text):
if self.focus and text != u'\r':
self.focus.dispatch_event('on_text', text)
def on_text_motion(self, motion):
if self.focus:
self.focus.dispatch_event('on_text_motion', motion)
def on_text_motion_select(self, motion):
if self.focus:
self.focus.dispatch_event('on_text_motion_select', motion)
def on_update(self, dt):
"""
We update our layout only when it's time to construct another frame.
Since we may receive several resize events within this time, this
ensures we don't resize too often.
@param dialog The Dialog containing the controls
@param dt Time passed since last update event (in seconds)
"""
for control in self.controls:
control.dispatch_event('on_update', dt)
def set_focus(self, focus):
"""
Sets a new focus, dispatching lose and gain focus events appropriately
@param focus The new focus, or None if no focus
"""
if self.focus == focus:
return
if self.focus is not None:
self.focus.dispatch_event('on_lose_focus')
self.focus = focus
if focus is not None:
focus.dispatch_event('on_gain_focus')
def set_hover(self, hover):
"""
Sets a new highlight, dispatching lose and gain highlight events
appropriately
@param hover The new highlight, or None if no highlight
"""
if self.hover == hover:
return
if self.hover is not None:
self.hover.dispatch_event('on_lose_highlight')
self.hover = hover
if hover is not None:
hover.dispatch_event('on_gain_highlight')
def set_wheel_hint(self, control):
self.wheel_hint = control
def set_wheel_target(self, control):
self.wheel_target = control
def teardown(self):
self.controls = []
self.control_map = {}
self.focus = None
self.hover = None
self.wheel_hint = None
self.wheel_target = None
def update_controls(self):
"""Update our list of controls which may respond to user input."""
controls = self._get_controls()
self.controls = []
self.control_areas = {}
self.control_map = {}
for control, left, right, top, bottom in controls:
self.controls.append(control)
self.control_areas[control] = (left, right, top, bottom)
if control.id is not None:
self.control_map[control.id] = control
if self.hover is not None and self.hover not in self.controls:
self.set_hover(None)
if self.focus is not None and self.focus not in self.controls:
self.set_focus(None)
kytten_next_dialog_order_id = 0
def GetNextDialogOrderId():
global kytten_next_dialog_order_id
kytten_next_dialog_order_id += 1
return kytten_next_dialog_order_id
class DialogGroup(pyglet.graphics.OrderedGroup):
"""
Ensure that all Widgets within a Dialog can be drawn with
blending enabled, and that our Dialog will be drawn in a particular
order relative to other Dialogs.
"""
def __init__(self, parent=None):
"""
Creates a new DialogGroup. By default we'll be on top.
@param parent Parent group
"""
pyglet.graphics.OrderedGroup.__init__(
self, GetNextDialogOrderId(), parent)
self.real_order = self.order
def __cmp__(self, other):
"""
When compared with other DialogGroups, we'll return our real order
compared against theirs; otherwise use the OrderedGroup comparison.
"""
if isinstance(other, DialogGroup):
return cmp(self.real_order, other.real_order)
else:
return OrderedGroup.__cmp__(self, other)
def is_on_top(self):
"""
Are we the top dialog group?
"""
global kytten_next_dialog_order_id
return self.real_order == kytten_next_dialog_order_id
def pop_to_top(self):
"""
Put us on top of other dialog groups.
"""
self.real_order = GetNextDialogOrderId()
def set_state(self):
"""
Ensure that blending is set.
"""
gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_CURRENT_BIT)
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
def unset_state(self):
"""
Restore previous blending state.
"""
gl.glPopAttrib()
class Dialog(Wrapper, DialogEventManager):
"""
Defines a new GUI. By default it can contain only one element, but that
element can be a Layout of some kind which can contain multiple elements.
Pass a Theme in to set the graphic appearance of the Dialog.
The Dialog is always repositioned in relationship to the window, and
handles resize events accordingly.
"""
def __init__(self, content=None, window=None, batch=None, group=None,
anchor=ANCHOR_CENTER, offset=(0, 0), parent=None,
theme=None, movable=True, on_enter=None, on_escape=None):
"""
Creates a new dialog.
@param content The Widget which we wrap
@param window The window to which we belong; used to set the
mouse cursor when appropriate. If set, we will
add ourself to the window as a handler.
@param batch Batch in which we are to place our graphic elements;
may be None if we are to create our own Batch
@param group Group in which we are to place our graphic elements;
may be None
@param anchor Anchor point of the window, relative to which we
are positioned. If ANCHOR_TOP_LEFT is specified,
our top left corner will be aligned to the window's
top left corner; if ANCHOR_CENTER is specified,
our center will be aligned to the window's center,
and so forth.
@param offset Offset from the anchor point. A positive X is always
to the right, a positive Y to the upward direction.
@param theme The Theme which we are to use to generate our graphical
appearance.
@param movable True if the dialog is able to be moved
@param on_enter Callback for when user presses enter on the last
input within this dialog, i.e. form submit
@param on_escape Callback for when user presses escape
"""
assert isinstance(theme, dict)
Wrapper.__init__(self, content=content)
DialogEventManager.__init__(self)
self.window = window
self.anchor = anchor
self.offset = offset
self.theme = theme
self.is_movable = movable
self.on_enter = on_enter
self.on_escape = on_escape
if batch is None:
self.batch = pyglet.graphics.Batch()
self.own_batch = True
else:
self.batch = batch
self.own_batch = False
self.root_group = DialogGroup(parent=group)
self.panel_group = pyglet.graphics.OrderedGroup(0, self.root_group)
self.bg_group = pyglet.graphics.OrderedGroup(1, self.root_group)
self.fg_group = pyglet.graphics.OrderedGroup(2, self.root_group)
self.highlight_group = pyglet.graphics.OrderedGroup(3, self.root_group)
self.needs_layout = True
self.is_dragging = False
if window is None:
self.screen = Widget()
else:
width, height = window.get_size()
self.screen = Widget(width=width, height=height)
window.push_handlers(self)
def do_layout(self):
"""
We lay out the Dialog by first determining the size of all its
chlid Widgets, then laying ourself out relative to the parent window.
"""
# Determine size of all components
self.size(self)
# Calculate our position relative to our containing window,
# making sure that we fit completely on the window. If our offset
# would send us off the screen, constrain it.
x, y = GetRelativePoint(self.screen, self.anchor,
self, None, (0, 0))
max_offset_x = self.screen.width - self.width - x
max_offset_y = self.screen.height - self.height - y
offset_x, offset_y = self.offset
offset_x = max(min(offset_x, max_offset_x), -x)
offset_y = max(min(offset_y, max_offset_y), -y)
self.offset = (offset_x, offset_y)
x += offset_x
y += offset_y
# Perform the actual layout now!
self.layout(x, y)
self.update_controls()
self.needs_layout = False
def draw(self):
assert self.own_batch
self.batch.draw()
def ensure_visible(self, control):
"""
Ensure a control is visible. For Dialog, this doesn't matter
since we don't scroll.
"""
pass
def get_root(self):
return self
def on_key_press(self, symbol, modifiers):
"""
We intercept TAB, ENTER, and ESCAPE events. TAB and ENTER will
move us between fields, holding shift will reverse the direction
of our iteration. ESCAPE may cause us to send an on_escape
callback.
Otherwise, we pass key presses to our child elements.
@param symbol Key pressed
@param modifiers Modifiers for key press
"""
retval = DialogEventManager.on_key_press(self, symbol, modifiers)
if not retval:
if symbol in [pyglet.window.key.TAB, pyglet.window.key.ENTER]:
if self.on_enter is not None:
self.on_enter(self)
return pyglet.event.EVENT_HANDLED
elif symbol == pyglet.window.key.ESCAPE:
if self.on_escape is not None:
self.on_escape(self)
return pyglet.event.EVENT_HANDLED
return retval
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
"""
Handles mouse dragging. If we have a focus, pass it in. Otherwise
if we are movable, and we were being dragged, move the window.
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param dx Delta X
@param dy Delta Y
@param buttons Buttons held while moving
@param modifiers Modifiers to apply to buttons
"""
if not DialogEventManager.on_mouse_drag(self, x, y, dx, dy,
buttons, modifiers):
if self.is_movable and self.is_dragging:
x, y = self.offset
self.offset = (int(x + dx), int(y + dy))
self.set_needs_layout()
return pyglet.event.EVENT_HANDLED
def on_mouse_press(self, x, y, button, modifiers):
"""
If the focus is set, and the target lies within the focus, pass the
message down. Otherwise, check if we need to assign a new focus.
If the mouse was pressed within our frame but no control was targeted,
we may be setting up to drag the Dialog around.
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param button Button pressed
@param modifiers Modifiers to apply to button
"""
retval = DialogEventManager.on_mouse_press(self, x, y,
button, modifiers)
if self.hit_test(x, y):
if not self.root_group.is_on_top():
self.pop_to_top()
if not retval:
self.is_dragging = True
retval = pyglet.event.EVENT_HANDLED
return retval
def on_mouse_release(self, x, y, button, modifiers):
"""
Button was released. We pass this along to the focus, then we
generate an on_mouse_motion to handle changing the highlighted
Control if necessary.
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param button Button released
@param modifiers Modifiers to apply to button
"""
self.is_dragging = False
return DialogEventManager.on_mouse_release(self, x, y,
button, modifiers)
def on_resize(self, width, height):
"""
Update our knowledge of the window's width and height.
@param width Width of the window
@param height Height of the window
"""
if self.screen.width != width or self.screen.height != height:
self.screen.width, self.screen.height = width, height
self.needs_layout = True
def on_update(self, dt):
"""
We update our layout only when it's time to construct another frame.
Since we may receive several resize events within this time, this
ensures we don't resize too often.
@param dt Time passed since last update event (in seconds)
"""
if self.needs_layout:
self.do_layout()
DialogEventManager.on_update(self, dt)
def pop_to_top(self):
"""
Pop our dialog group to the top, and force our batch to re-sort
the groups. Also, puts our event handler on top of the window's
event handler stack.
"""
self.root_group.pop_to_top()
self.batch._draw_list_dirty = True # forces resorting groups
if self.window is not None:
self.window.remove_handlers(self)
self.window.push_handlers(self)
def set_needs_layout(self):
"""
True if we should redo the Dialog layout on our next update.
"""
self.needs_layout = True
def teardown(self):
DialogEventManager.teardown(self)
if self.content is not None:
self.content.teardown()
self.content = None
if self.window is not None:
self.window.remove_handlers(self)
self.window = None
self.batch._draw_list_dirty = True # forces resorting groups
class PopupMessage(Dialog):
"""A simple fire-and-forget dialog."""
def __init__(self, text="", window=None, batch=None, group=None,
theme=None, on_escape=None):
def on_ok(dialog=None):
if on_escape is not None:
on_escape(self)
self.teardown()
return Dialog.__init__(self, content=Frame(
VerticalLayout([
Label(text),
Button("Ok", on_click=on_ok),
])),
window=window, batch=batch, group=group,
theme=theme, movable=True,
on_enter=on_ok, on_escape=on_ok)
class PopupConfirm(Dialog):
"""An ok/cancel-style dialog. Escape defaults to cancel."""
def __init__(self, text="", ok="Ok", cancel="Cancel",
window=None, batch=None, group=None, theme=None,
on_ok=None, on_cancel=None):
def on_ok_click(dialog=None):
if on_ok is not None:
on_ok(self)
self.teardown()
def on_cancel_click(dialog=None):
if on_cancel is not None:
on_cancel(self)
self.teardown()
return Dialog.__init__(self, content=Frame(
VerticalLayout([
Label(text),
HorizontalLayout([
Button(ok, on_click=on_ok_click),
None,
Button(cancel, on_click=on_cancel_click)
]),
])),
window=window, batch=batch, group=group,
theme=theme, movable=True,
on_enter=on_ok_click, on_escape=on_cancel_click) | Python |
# safe_eval
# Copyrighted (C) Michael Spencer
#
# Source: http://code.activestate.com/recipes/364469/
import compiler
class Unsafe_Source_Error(Exception):
def __init__(self,error,descr = None,node = None):
self.error = error
self.descr = descr
self.node = node
self.lineno = getattr(node,"lineno",None)
def __repr__(self):
return "Line %d. %s: %s" % (self.lineno, self.error, self.descr)
__str__ = __repr__
class SafeEval(object):
def visit(self, node,**kw):
cls = node.__class__
meth = getattr(self,'visit'+cls.__name__,self.default)
return meth(node, **kw)
def default(self, node, **kw):
for child in node.getChildNodes():
return self.visit(child, **kw)
visitExpression = default
def visitConst(self, node, **kw):
return node.value
def visitDict(self, node,**kw):
return dict([(self.visit(k),self.visit(v)) for k,v in node.items])
def visitTuple(self, node, **kw):
return tuple(self.visit(i) for i in node.nodes)
def visitList(self, node, **kw):
return [self.visit(i) for i in node.nodes]
def visitUnarySub(self, node, **kw):
return -self.visit(node.expr)
class SafeEvalWithErrors(SafeEval):
def default(self, node, **kw):
raise Unsafe_Source_Error("Unsupported source construct",
node.__class__,node)
def visitName(self,node, **kw):
raise Unsafe_Source_Error("Strings must be quoted",
node.name, node)
# Add more specific errors if desired
def safe_eval(source, fail_on_error = True):
walker = fail_on_error and SafeEvalWithErrors() or SafeEval()
try:
ast = compiler.parse(source,"eval")
except SyntaxError, err:
raise Unsafe_Source_Error(err, source)
try:
return walker.visit(ast)
except Unsafe_Source_Error, err:
raise | Python |
# kytten/input.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import pyglet
from widgets import Control
from override import KyttenInputLabel
class Input(Control):
"""A text input field."""
def __init__(self, id=None, text="", length=20, max_length=None, padding=0,
on_input=None, disabled=False):
Control.__init__(self, id=id, disabled=disabled)
self.text = text
self.length = length
self.max_length = max_length
self.padding = padding
self.on_input = on_input
self.document = pyglet.text.document.UnformattedDocument(text)
self.document_style_set = False
self.text_layout = None
self.label = None
self.caret = None
self.field = None
self.highlight = None
def delete(self):
Control.delete(self)
if self.caret is not None:
self.caret.delete()
self.caret = None
if self.text_layout is not None:
self.document.remove_handlers(self.text_layout)
self.text_layout.delete()
self.text_layout = None
if self.label is not None:
self.label.delete()
self.label = None
if self.field is not None:
self.field.delete()
self.field = None
if self.highlight is not None:
self.highlight.delete()
self.highlight = None
def disable(self):
Control.disable(self)
self.document_style_set = False
def enable(self):
Control.enable(self)
self.document_style_set = False
def get_text(self):
return self.document.text
def get_value(self):
return self.get_text()
def is_focusable(self):
return True
def is_input(self):
return True
def layout(self, x, y):
self.x, self.y = x, y
self.field.update(x, y, self.width, self.height)
if self.highlight is not None:
self.highlight.update(x, y, self.width, self.height)
x, y, width, height = self.field.get_content_region()
if self.is_focus():
self.text_layout.begin_update()
self.text_layout.x = x + self.padding
self.text_layout.y = y + self.padding
self.text_layout.end_update()
else:
# Adjust the text for font's descent
descent = self.document.get_font().descent
self.label.begin_update()
self.label.x = x + self.padding
self.label.y = y + self.padding - descent
self.label.width = width - self.padding * 2
self.label.end_update()
def on_gain_highlight(self):
Control.on_gain_highlight(self)
self.set_highlight()
def on_gain_focus(self):
Control.on_gain_focus(self)
self.delete()
if self.saved_dialog is not None:
self.size(self.saved_dialog)
self.layout(self.x, self.y)
def on_key_press(self, symbol, modifiers):
return pyglet.event.EVENT_HANDLED
def on_lose_focus(self):
Control.on_lose_focus(self)
self.delete()
if self.saved_dialog is not None:
self.size(self.saved_dialog)
self.layout(self.x, self.y)
if self.on_input is not None:
if self.id is not None:
self.on_input(self.id, self.get_text())
else:
self.on_input(self.get_text())
def on_lose_highlight(self):
Control.on_lose_highlight(self)
self.remove_highlight()
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
if not self.is_disabled() and self.caret:
return self.caret.on_mouse_drag(x, y, dx, dy, buttons, modifiers)
def on_mouse_press(self, x, y, button, modifiers):
if not self.is_disabled():
return self.caret.on_mouse_press(x, y, button, modifiers)
def on_text(self, text):
if not self.is_disabled() and self.caret:
self.caret.on_text(text)
if self.max_length and len(self.document.text) > self.max_length:
self.document.text = self.document.text[:self.max_length]
self.caret.mark = self.caret.position = self.max_length
def on_text_motion(self, motion):
if not self.is_disabled() and self.caret:
return self.caret.on_text_motion(motion)
def on_text_motion_select(self, motion):
if not self.is_disabled() and self.caret:
return self.caret.on_text_motion_select(motion)
def set_text(self, text):
self.document.text = text
if self.caret:
self.caret.mark = self.caret.position = len(self.document.text)
elif self.label:
self.label.text = text
def remove_highlight(self):
if not self.is_highlight() and not self.is_focus():
if self.highlight is not None:
self.highlight.delete()
self.highlight = None
def set_highlight(self):
path = ['input', 'highlight']
if self.highlight is None:
self.highlight = self.saved_dialog.theme[path]['image'].generate(
color=self.saved_dialog.theme[path]['highlight_color'],
batch=self.saved_dialog.batch,
group=self.saved_dialog.highlight_group)
self.highlight.update(self.x, self.y, self.width, self.height)
def size(self, dialog):
if dialog is None:
return
Control.size(self, dialog)
if self.is_disabled():
color = dialog.theme['input']['disabled_color']
else:
color = dialog.theme['input']['text_color']
# We set the style once. We shouldn't have to do so again because
# it's an UnformattedDocument.
if not self.document_style_set:
self.document.set_style(0, len(self.document.text),
dict(color=color,
font_name=dialog.theme['font'],
font_size=dialog.theme['font_size']))
self.document_style_set = True
# Calculate the needed size based on the font size
font = self.document.get_font(0)
height = font.ascent - font.descent
glyphs = font.get_glyphs('A_')
width = max([x.width for x in glyphs])
needed_width = self.length * width + 2 * self.padding
needed_height = height + 2 * self.padding
if self.is_focus():
if self.text_layout is None:
self.text_layout = pyglet.text.layout.IncrementalTextLayout(
self.document, needed_width, needed_height,
multiline=False,
batch=dialog.batch, group=dialog.fg_group)
assert self.caret is None
assert self.label is None
if self.caret is None:
self.caret = pyglet.text.caret.Caret(
self.text_layout,
color=dialog.theme['input']['gui_color'][0:3])
self.caret.visible = True
self.caret.mark = 0
self.caret.position = len(self.document.text)
else:
if self.label is None:
self.label = KyttenInputLabel(self.document.text,
multiline=False,
width=self.width-self.padding*2,
color=color,
batch=dialog.batch,
group=dialog.fg_group)
assert self.text_layout is None and self.caret is None
if self.field is None:
if self.is_disabled():
color = dialog.theme['input']['disabled_color']
else:
color = dialog.theme['input']['gui_color']
self.field = dialog.theme['input']['image'].generate(
color=color,
batch=dialog.batch,
group=dialog.bg_group)
if self.highlight is None and self.is_highlight():
self.set_highlight()
self.width, self.height = self.field.get_needed_size(
needed_width, needed_height)
def teardown(self):
self.on_input = False
Control.teardown(self) | Python |
# kytten/widgets.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
# Simple widgets belong in this file, to avoid cluttering the directory with
# many small files. More complex widgets should be placed in separate files.
# Widget: the base GUI element. A fixed area of space.
# Control: a Widget which accepts events.
# Test: a Widget which draws a crossed box within its area.
# Spacer: a Widget which can expand to fill available space. Useful to
# push other Widgets in a layout to the far right or bottom.
# Graphic: a Widget with a texture drawn over its surface. Can be expanded.
# Label: a Widget which wraps a simple text label.
import pyglet
from pyglet import gl
from override import KyttenLabel
class Widget:
"""
The base of all Kytten GUI elements. Widgets correspond to areas on the
screen and may (in the form of Controls) respond to user input.
A simple Widget can be used as a fixed-area spacer.
Widgets are constructed in two passes: first, they are created and
passed into a Dialog, or added to a Dialog or one of its children,
then the Dialog calls their size() method to get their size and their
layout() method to place them on the screen. When their size is gotten
for the first time, they initialize any requisite graphic elements
that could not be done at creation time.
"""
def __init__(self, width=0, height=0):
"""
Creates a new Widget.
@param width Initial width
@param height Initial height
"""
self.x = self.y = 0
self.width = width
self.height = height
self.saved_dialog = None
def _get_controls(self):
"""
Return this widget if it is a Control, or any children which
are Controls.
"""
return []
def delete(self):
"""
Deletes any graphic elements we have constructed. Note that
we may be asked to recreate them later.
"""
pass
def ensure_visible(self):
if self.saved_dialog is not None:
self.saved_dialog.ensure_visible(self)
def expand(self, width, height):
"""
Expands the widget to fill the specified space given.
@param width Available width
@param height Available height
"""
assert False, "Widget does not support expand"
def hit_test(self, x, y):
"""
True if the given point lies within our area.
@param x X coordinate of point
@param y Y coordinate of point
@returns True if the point is within our area
"""
return x >= self.x and x < self.x + self.width and \
y >= self.y and y < self.y + self.height
def is_expandable(self):
"""
Returns true if the widget can expand to fill available space.
"""
return False
def is_focusable(self):
"""
Return true if the widget can be tabbed to and accepts keyboard
input
"""
return False
def is_input(self):
"""
Returns true if the widget accepts an input and can return a value
"""
return False
def layout(self, x, y):
"""
Assigns a new location to this widget.
@param x X coordinate of our lower left corner
@param y Y coordinate of our lower left corner
"""
self.x, self.y = x, y
def size(self, dialog):
"""
Constructs any graphic elements needed, and recalculates our size
if necessary.
@param dialog The Dialog which contains this Widget
"""
if dialog != self and dialog is not None:
self.saved_dialog = dialog
def teardown(self):
"""
Removes all resources and pointers to other GUI widgets.
"""
self.delete()
self.saved_dialog = None
class Control(Widget, pyglet.event.EventDispatcher):
"""
Controls are widgets which can accept events.
Dialogs will search their children for a list of controls, and will
then dispatch events to whichever control is currently the focus of
the user's attention.
"""
def __init__(self, id=None, value=None, width=0, height=0, disabled=False):
"""
Creates a new Control.
@param id Controls may have ids, which can be used to identify
them to the outside application.
@param value Controls may be assigned values at start time. The
values of all controls which have ids can be obtained
through the containing Dialog.
@param x Initial X coordinate of lower left corner
@param y Initial Y coordinate of lower left corner
@param width Initial width
@param height Initial height
@param disabled True if control should be disabled
"""
Widget.__init__(self, width, height)
self.id = id
self.value = value
self.disabled_flag = disabled
pyglet.event.EventDispatcher.__init__(self)
self.highlight_flag = False
self.focus_flag = False
def _get_controls(self):
return [(self, self.x, self.x + self.width, # control, left, right,
self.y + self.height, self.y)] # top, bottom
def disable(self):
self.disabled_flag = True
self.delete()
if self.saved_dialog is not None:
self.saved_dialog.set_needs_layout()
def enable(self):
self.disabled_flag = False
self.delete()
if self.saved_dialog is not None:
self.saved_dialog.set_needs_layout()
def get_cursor(self, x, y):
return self.cursor
def is_disabled(self):
return self.disabled_flag
def is_focus(self):
return self.focus_flag
def is_highlight(self):
return self.highlight_flag
def on_gain_focus(self):
self.focus_flag = True
def on_gain_highlight(self):
self.highlight_flag = True
def on_lose_focus(self):
self.focus_flag = False
def on_lose_highlight(self):
self.highlight_flag = False
# Controls can potentially accept most of the events defined for the window,
# but in practice we'll only pass selected events from Dialog. This avoids
# a large number of unsightly empty method declarations.
for event_type in pyglet.window.Window.event_types:
Control.register_event_type(event_type)
Control.register_event_type('on_gain_focus')
Control.register_event_type('on_gain_highlight')
Control.register_event_type('on_lose_focus')
Control.register_event_type('on_lose_highlight')
Control.register_event_type('on_update')
class Spacer(Widget):
"""
A Spacer is an empty widget that expands to fill space in layouts.
Use Widget if you need a fixed-sized spacer.
"""
def __init__(self, width=0, height=0):
"""
Creates a new Spacer. The width and height given are the minimum
area that we must cover.
@param width Minimum width
@param height Minimum height
"""
Widget.__init__(self)
self.min_width, self.min_height = width, height
def expand(self, width, height):
"""
Expand the spacer to fill the maximum space.
@param width Available width
@param height Available height
"""
self.width, self.height = width, height
def is_expandable(self):
"""Indicates the Spacer can be expanded"""
return True
def size(self, dialog):
"""Spacer shrinks down to the minimum size for placement.
@param dialog Dialog which contains us"""
if dialog is None:
return
Widget.size(self, dialog)
self.width, self.height = self.min_width, self.min_height
class Graphic(Widget):
"""
Lays out a graphic from the theme, i.e. part of a title bar.
"""
def __init__(self, path, is_expandable=False):
Widget.__init__(self)
self.path = path
self.expandable=is_expandable
self.graphic = None
self.min_width = self.min_height = 0
def delete(self):
if self.graphic is not None:
self.graphic.delete()
self.graphic = None
def expand(self, width, height):
if self.expandable:
self.width, self.height = width, height
self.graphic.update(self.x, self.y, self.width, self.height)
def is_expandable(self):
return self.expandable
def layout(self, x, y):
self.x, self.y = x, y
self.graphic.update(x, y, self.width, self.height)
def size(self, dialog):
if dialog is None:
return
Widget.size(self, dialog)
if self.graphic is None:
template = dialog.theme[self.path]['image']
self.graphic = template.generate(
dialog.theme[self.path]['gui_color'],
dialog.batch,
dialog.fg_group)
self.min_width = self.graphic.width
self.min_height = self.graphic.height
self.width, self.height = self.min_width, self.min_height
class Label(Widget):
"""A wrapper around a simple text label."""
def __init__(self, text="", bold=False, italic=False,
font_name=None, font_size=None, color=None, path=[]):
Widget.__init__(self)
self.text = text
self.bold = bold
self.italic = italic
self.font_name = font_name
self.font_size = font_size
self.color = color
self.path = path
self.label = None
def delete(self):
if self.label is not None:
self.label.delete()
self.label = None
def layout(self, x, y):
Widget.layout(self, x, y)
font = self.label.document.get_font()
self.label.x = x
self.label.y = y - font.descent
def size(self, dialog):
if dialog is None:
return
Widget.size(self, dialog)
if self.label is None:
self.label = KyttenLabel(
self.text, bold=self.bold, italic=self.italic,
color=self.color or
dialog.theme[self.path + ['gui_color']],
font_name=self.font_name or
dialog.theme[self.path + ['font']],
font_size=self.font_size or
dialog.theme[self.path + ['font_size']],
batch=dialog.batch, group=dialog.fg_group)
font = self.label.document.get_font()
self.width = self.label.content_width
self.height = font.ascent - font.descent # descent is negative
| Python |
# kytten/override.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import pyglet
KYTTEN_LAYOUT_GROUPS = {}
KYTTEN_LAYOUT_GROUP_REFCOUNTS = {}
def GetKyttenLayoutGroups(group):
if not KYTTEN_LAYOUT_GROUPS.has_key(group):
top_group = pyglet.text.layout.TextLayoutGroup(group)
background_group = pyglet.graphics.OrderedGroup(0, top_group)
foreground_group = \
pyglet.text.layout.TextLayoutForegroundGroup(1, top_group)
foreground_decoration_group = \
pyglet.text.layout.TextLayoutForegroundDecorationGroup(
2, top_group)
KYTTEN_LAYOUT_GROUPS[group] = (top_group,
background_group,
foreground_group,
foreground_decoration_group)
KYTTEN_LAYOUT_GROUP_REFCOUNTS[group] = 0
KYTTEN_LAYOUT_GROUP_REFCOUNTS[group] += 1
return KYTTEN_LAYOUT_GROUPS[group]
def ReleaseKyttenLayoutGroups(group):
KYTTEN_LAYOUT_GROUP_REFCOUNTS[group] -= 1
if not KYTTEN_LAYOUT_GROUP_REFCOUNTS[group]:
del KYTTEN_LAYOUT_GROUP_REFCOUNTS[group]
del KYTTEN_LAYOUT_GROUPS[group]
class KyttenLabel(pyglet.text.Label):
def _init_groups(self, group):
if not group:
return # use the default groups
self.top_group, self.background_group, self.foreground_group, \
self.foreground_decoration_group = GetKyttenLayoutGroups(group)
def teardown(self):
pyglet.text.Label.teardown(self)
group = self.top_group.parent
if group is not None:
ReleaseKyttenLayoutGroups(group)
self.top_group = self.background_self = self.foreground_group \
= self.foreground_decoration_group = None
class KyttenInputLabel(KyttenLabel):
def _get_left(self):
if self._multiline:
width = self._width
else:
width = self.content_width
if self.width and width > self.width:
# align to right edge, clip left
return self._x + self.width - width
if self._anchor_x == 'left':
return self._x
elif self._anchor_x == 'center':
return self._x - width // 2
elif self._anchor_x == 'right':
return self._x - width
else:
assert False, 'Invalid anchor_x'
def _update(self):
pyglet.text.Label._update(self)
# Iterate through our vertex lists and break if we need to clip
remove = []
if self.width and not self._multiline:
for vlist in self._vertex_lists:
num_quads = len(vlist.vertices) / 8
remove_quads = 0
has_quads = False
for n in xrange(0, num_quads):
x1, y1, x2, y2, x3, y3, x4, y4 = vlist.vertices[n*8:n*8+8]
tx1, ty1, tz1, tx2, ty2, tz2, \
tx3, ty3, tz3, tx4, ty4, tz4 = \
vlist.tex_coords[n*12:n*12+12]
if x2 >= self._x:
has_quads = True
m = n - remove_quads # shift quads left
if x1 < self._x: # clip on left side
percent = (float(self._x) - float(x1)) / \
(float(x2) - float(x1))
x1 = x4 = max(self._x, x1)
tx1 = tx4 = (tx2 - tx1) * percent + tx1
vlist.vertices[m*8:m*8+8] = \
[x1, y1, x2, y2, x3, y3, x4, y4]
vlist.tex_coords[m*12:m*12+12] = \
[tx1, ty1, tz1, tx2, ty2, tz2,
tx3, ty3, tz3, tx4, ty4, tz4]
else:
# We'll delete quads entirely not visible
remove_quads = remove_quads + 1
if remove_quads == num_quads:
remove.append(vlist)
elif remove_quads > 0:
vlist.resize((num_quads - remove_quads) * 4)
for vlist in remove:
vlist.delete()
self._vertex_lists.remove(vlist)
| Python |
# kytten/checkbox.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import pyglet
from widgets import Control
from layout import HALIGN_LEFT, HALIGN_RIGHT
from override import KyttenLabel
class Checkbox(Control):
"""
A two-state checkbox.
"""
def __init__(self, text="", is_checked=False, id=None,
align=HALIGN_RIGHT, padding=4, on_click=None,
disabled=False):
"""
Creates a new checkbox. The provided text will be used to caption the
checkbox.
@param text Label for the checkbox
@param is_checked True if we should start checked
@param id ID for value
@param align HALIGN_RIGHT if label should be right of checkbox,
HALIGN_LEFT if label should be left of checkbox
@param padding Space between checkbox and label
@param on_click Callback for the checkbox
@param disabled True if the checkbox should be disabled
"""
assert align in [HALIGN_LEFT, HALIGN_RIGHT]
Control.__init__(self, id=id, disabled=disabled)
self.text = text
self.is_checked = is_checked
self.align = align
self.padding = padding
self.on_click = on_click
self.label = None
self.checkbox = None
self.highlight = None
def delete(self):
"""
Clean up our graphic elements
"""
Control.delete(self)
if self.checkbox is not None:
self.checkbox.delete()
self.checkbox = None
if self.label is not None:
self.label.delete()
self.label = None
if self.highlight is not None:
self.highlight.delete()
self.highlight = None
def get_value(self):
return self.is_checked
def is_input(self):
return True
def layout(self, x, y):
"""
Places the Checkbox.
@param x X coordinate of lower left corner
@param y Y coordinate of lower left corner
"""
Control.layout(self, x, y)
if self.align == HALIGN_RIGHT: # label goes on right
self.checkbox.update(x, y + self.height/2 - self.checkbox.height/2,
self.checkbox.width, self.checkbox.height)
self.label.x = x + self.checkbox.width + self.padding
else: # label goes on left
self.label.x = x
self.checkbox.update(x + self.label.content_width + self.padding,
y + self.height/2 - self.checkbox.height/2,
self.checkbox.width, self.checkbox.height)
if self.highlight is not None:
self.highlight.update(self.x, self.y, self.width, self.height)
font = self.label.document.get_font()
height = font.ascent - font.descent
self.label.y = y + self.height/2 - height/2 - font.descent
def on_gain_highlight(self):
Control.on_gain_highlight(self)
self.size(self.saved_dialog)
self.highlight.update(self.x, self.y, self.width, self.height)
def on_lose_highlight(self):
Control.on_lose_highlight(self)
if self.highlight is not None:
self.highlight.delete()
self.highlight = None
def on_mouse_press(self, x, y, button, modifiers):
if not self.is_disabled():
self.is_checked = not self.is_checked
if self.on_click is not None:
if self.id is not None:
self.on_click(self.id, self.is_checked)
else:
self.on_click(self.is_checked)
# Delete the button to force it to be redrawn
self.delete()
self.saved_dialog.set_needs_layout()
def size(self, dialog):
"""
Sizes the Checkbox. If necessary, creates the graphic elements.
@param dialog Dialog which contains the Checkbox
"""
if dialog is None:
return
Control.size(self, dialog)
if self.is_checked:
path = ['checkbox', 'checked']
else:
path = ['checkbox', 'unchecked']
if self.is_disabled():
color = dialog.theme[path]['disabled_color']
else:
color = dialog.theme[path]['gui_color']
if self.checkbox is None:
self.checkbox = dialog.theme[path]['image'].generate(
color,
dialog.batch, dialog.bg_group)
if self.highlight is None and self.is_highlight():
self.highlight = dialog.theme[path]['highlight']['image'].generate(
dialog.theme[path]['highlight_color'],
dialog.batch,
dialog.bg_group)
if self.label is None:
self.label = KyttenLabel(self.text,
font_name=dialog.theme[path]['font'],
font_size=dialog.theme[path]['font_size'],
color=color,
batch=dialog.batch, group=dialog.fg_group)
# Treat the height of the label as ascent + descent
font = self.label.document.get_font()
height = font.ascent - font.descent # descent is negative
self.width = self.checkbox.width + self.padding + \
self.label.content_width
self.height = max(self.checkbox.height, height)
def teardown(self):
self.on_click = None
Control.teardown(self) | Python |
# kytten/scrollable.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import pyglet
from pyglet import gl
from dialog import DialogEventManager
from frame import Wrapper
from scrollbar import HScrollbar, VScrollbar
from widgets import Widget
class ScrollableGroup(pyglet.graphics.Group):
"""
We restrict what's shown within a Scrollable by performing a scissor
test.
"""
def __init__(self, x, y, width, height, parent=None):
"""Create a new ScrollableGroup
@param x X coordinate of lower left corner
@param y Y coordinate of lower left corner
@param width Width of scissored region
@param height Height of scissored region
@param parent Parent group
"""
pyglet.graphics.Group.__init__(self, parent)
self.x, self.y, self.width, self.height = x, y, width, height
self.was_scissor_enabled = False
def set_state(self):
"""
Enables a scissor test on our region
"""
gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_TRANSFORM_BIT |
gl.GL_CURRENT_BIT)
self.was_scissor_enabled = gl.glIsEnabled(gl.GL_SCISSOR_TEST)
gl.glEnable(gl.GL_SCISSOR_TEST)
gl.glScissor(int(self.x), int(self.y),
int(self.width), int(self.height))
def unset_state(self):
"""
Disables the scissor test
"""
if not self.was_scissor_enabled:
gl.glDisable(gl.GL_SCISSOR_TEST)
gl.glPopAttrib()
class Scrollable(Wrapper):
"""
Wraps a layout or widget and limits it to a maximum, or fixed, size.
If the layout exceeds the viewable limits then it is truncated and
scrollbars will be displayed so the user can pan around.
"""
def __init__(self, content=None, width=None, height=None,
is_fixed_size=False, always_show_scrollbars=False):
"""
Creates a new Scrollable.
@param content The layout or Widget to be scrolled
@param width Maximum width, or None
@param height Maximum height, or None
@param is_fixed_size True if we should always be at maximum size;
otherwise we shrink to match our content
@param always_show_scrollbars True if we should always show scrollbars
"""
if is_fixed_size:
assert width is not None and height is not None
Wrapper.__init__(self, content)
self.max_width = width
self.max_height = height
self.is_fixed_size = is_fixed_size
self.always_show_scrollbars = always_show_scrollbars
self.hscrollbar = None
self.vscrollbar = None
self.content_width = 0
self.content_height = 0
self.content_x = 0
self.content_y = 0
self.hscrollbar_height = 0
self.vscrollbar_width = 0
# We emulate some aspects of Dialog here. We cannot just inherit
# from Dialog because pyglet event handling won't allow keyword
# arguments to be passed through.
self.theme = None
self.batch = None
self.root_group = None
self.panel_group = None
self.bg_group = None
self.fg_group = None
self.highlight_group = None
self.needs_layout = False
def _get_controls(self):
"""
We represent ourself as a Control to the Dialog, but we pass through
the events we receive from Dialog.
"""
base_controls = Wrapper._get_controls(self)
controls = []
our_left = self.content_x
our_right = our_left + self.content_width
our_bottom = self.content_y
our_top = our_bottom + self.content_height
for control, left, right, top, bottom in base_controls:
controls.append((control,
max(left, our_left),
min(right, our_right),
min(top, our_top),
max(bottom, our_bottom)))
if self.hscrollbar is not None:
controls += self.hscrollbar._get_controls()
if self.vscrollbar is not None:
controls += self.vscrollbar._get_controls()
return controls
def delete(self):
"""
Delete all graphical elements associated with the Scrollable
"""
Wrapper.delete(self)
if self.hscrollbar is not None:
self.hscrollbar.delete()
self.hscrollbar = None
if self.vscrollbar is not None:
self.vscrollbar.delete()
self.vscrollbar = None
self.root_group = None
self.panel_group = None
self.bg_group = None
self.fg_group = None
self.highlight_group = None
def ensure_visible(self, control):
"""
Make sure a control is visible.
"""
offset_x = 0
if self.hscrollbar:
offset_x = self.hscrollbar.get(self.content_width,
self.content.width)
offset_y = 0
if self.vscrollbar:
offset_y = self.content.height - self.content_height - \
self.vscrollbar.get(self.content_height,
self.content.height)
control_left = control.x - self.content_x - offset_x
control_right = control_left + control.width
control_bottom = control.y - self.content_y + offset_y
control_top = control_bottom + control.height
if self.hscrollbar is not None:
self.hscrollbar.ensure_visible(control_left, control_right,
max(self.content_width,
self.content.width))
if self.vscrollbar is not None:
self.vscrollbar.ensure_visible(control_top, control_bottom,
max(self.content_height,
self.content.height))
def expand(self, width, height):
if self.content.is_expandable():
if self.vscrollbar is not None:
self.content_width = width - self.vscrollbar_width
else:
self.content_width = width
if self.hscrollbar is not None:
self.content_height = height - self.hscrollbar_height
else:
self.content_height = height
self.content.expand(max(self.content_width, self.content.width),
max(self.content_height, self.content.height))
self.width, self.height = width, height
def get_root(self):
if self.saved_dialog:
return self.saved_dialog.get_root()
else:
return self
def hit_test(self, x, y):
"""
We only intercept events for the content region, not for
our scrollbars. They can handle themselves!
"""
return x >= self.content_x and y >= self.content_y and \
x < self.content_x + self.content_width and \
y < self.content_y + self.content_height
def is_expandable(self):
return True
def layout(self, x, y):
"""
Reposition the Scrollable
@param x X coordinate of lower left corner
@param y Y coordinate of lower left corner
"""
self.x, self.y = x, y
# Work out the adjusted content width and height
if self.hscrollbar is not None:
self.hscrollbar.layout(x, y)
y += self.hscrollbar.height
if self.vscrollbar is not None:
self.vscrollbar.layout(
x + self.content_width, y)
# Set the scissor group
self.root_group.x, self.root_group.y = x - 1, y - 1
self.root_group.width = self.content_width + 1
self.root_group.height = self.content_height + 1
# Work out the content layout
self.content_x, self.content_y = x, y
left = x
top = y + self.content_height - self.content.height
if self.hscrollbar:
left -= self.hscrollbar.get(self.content_width,
self.content.width)
if self.vscrollbar:
top += self.vscrollbar.get(self.content_height,
self.content.height)
self.content.layout(left, top)
self.needs_layout = False
def on_update(self, dt):
"""
On updates, we redo the layout if scrollbars have changed position
@param dt Time passed since last update event (in seconds)
"""
if self.needs_layout:
width, height = self.width, self.height
self.size(self.saved_dialog)
self.expand(width, height)
self.layout(self.x, self.y)
def set_needs_layout(self):
self.needs_layout = True
if self.saved_dialog is not None:
self.saved_dialog.set_needs_layout()
def set_wheel_hint(self, control):
if self.saved_dialog is not None:
self.saved_dialog.set_wheel_hint(control)
def set_wheel_target(self, control):
if self.saved_dialog is not None:
self.saved_dialog.set_wheel_target(control)
def size(self, dialog):
"""
Recalculate the size of the Scrollable.
@param dialog Dialog which contains us
"""
if dialog is None:
return
Widget.size(self, dialog)
if self.is_fixed_size:
self.width, self.height = self.max_width, self.max_height
self.hscrollbar_height = \
dialog.theme['hscrollbar']['left']['image'].height
self.vscrollbar_width = \
dialog.theme['vscrollbar']['up']['image'].width
if self.root_group is None: # do we need to re-clone dialog groups?
self.theme = dialog.theme
self.batch = dialog.batch
self.root_group = ScrollableGroup(0, 0, self.width, self.height,
parent=dialog.fg_group)
self.panel_group = pyglet.graphics.OrderedGroup(
0, self.root_group)
self.bg_group = pyglet.graphics.OrderedGroup(
1, self.root_group)
self.fg_group = pyglet.graphics.OrderedGroup(
2, self.root_group)
self.highlight_group = pyglet.graphics.OrderedGroup(
3, self.root_group)
Wrapper.delete(self) # force children to abandon old groups
Wrapper.size(self, self) # all children are to use our groups
if self.always_show_scrollbars or \
(self.max_width and self.width > self.max_width):
if self.hscrollbar is None:
self.hscrollbar = HScrollbar(self.max_width)
else:
if self.hscrollbar is not None:
self.hscrollbar.delete()
self.hscrollbar = None
if self.always_show_scrollbars or \
(self.max_height and self.height > self.max_height):
if self.vscrollbar is None:
self.vscrollbar = VScrollbar(self.max_height)
else:
if self.vscrollbar is not None:
self.vscrollbar.delete()
self.vscrollbar = None
self.width = min(self.max_width or self.width, self.width)
self.content_width = self.width
self.height = min(self.max_height or self.height, self.height)
self.content_height = self.height
if self.hscrollbar is not None:
self.hscrollbar.size(dialog)
self.hscrollbar.set(self.max_width, max(self.content.width,
self.max_width))
self.height += self.hscrollbar.height
if self.vscrollbar is not None:
self.vscrollbar.size(dialog)
self.vscrollbar.set(self.max_height, max(self.content.height,
self.max_height))
self.width += self.vscrollbar.width
| Python |
# kytten/layout.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
# Layouts are arrangements of multiple Widgets.
#
# VerticalLayout: a stack of Widgets, one on top of another.
# HorizontalLayout: a row of Widgets, side by side.
# GridLayout: a table of Widgets.
# FreeLayout: an open area within which Widgets may be positioned freely,
# relative to one of its anchor points.
import pyglet
from pyglet import gl
from widgets import Widget, Control, Spacer, Graphic, Label
# GUI layout constants
VALIGN_TOP = 1
VALIGN_CENTER = 0
VALIGN_BOTTOM = -1
HALIGN_LEFT = -1
HALIGN_CENTER = 0
HALIGN_RIGHT = 1
ANCHOR_TOP_LEFT = (VALIGN_TOP, HALIGN_LEFT)
ANCHOR_TOP = (VALIGN_TOP, HALIGN_CENTER)
ANCHOR_TOP_RIGHT = (VALIGN_TOP, HALIGN_RIGHT)
ANCHOR_LEFT = (VALIGN_CENTER, HALIGN_LEFT)
ANCHOR_CENTER = (VALIGN_CENTER, HALIGN_CENTER)
ANCHOR_RIGHT = (VALIGN_CENTER, HALIGN_RIGHT)
ANCHOR_BOTTOM_LEFT = (VALIGN_BOTTOM, HALIGN_LEFT)
ANCHOR_BOTTOM = (VALIGN_BOTTOM, HALIGN_CENTER)
ANCHOR_BOTTOM_RIGHT = (VALIGN_BOTTOM, HALIGN_RIGHT)
def GetRelativePoint(parent, parent_anchor, child, child_anchor, offset):
valign, halign = parent_anchor or ANCHOR_CENTER
if valign == VALIGN_TOP:
y = parent.y + parent.height
elif valign == VALIGN_CENTER:
y = parent.y + parent.height / 2
else: # VALIGN_BOTTOM
y = parent.y
if halign == HALIGN_LEFT:
x = parent.x
elif halign == HALIGN_CENTER:
x = parent.x + parent.width / 2
else: # HALIGN_RIGHT
x = parent.x + parent.width
valign, halign = child_anchor or (valign, halign)
offset_x, offset_y = offset
if valign == VALIGN_TOP:
y += offset_y - child.height
elif valign == VALIGN_CENTER:
y += offset_y - child.height/2
else: # VALIGN_BOTTOM
y += offset_y
if halign == HALIGN_LEFT:
x += offset_x
elif halign == HALIGN_CENTER:
x += offset_x - child.width / 2
else: # HALIGN_RIGHT
x += offset_x - child.width
return (x, y)
class VerticalLayout(Widget):
"""
Arranges Widgets on top of each other, from top to bottom.
"""
def __init__(self, content=[], align=HALIGN_CENTER, padding=5):
"""
Creates a new VerticalLayout.
@param content A list of Widgets to be arranged
@param align HALIGN_LEFT if Widgets are to be left-justified,
HALIGN_CENTER if they should be centered, and
HALIGN_RIGHT if they are to be right-justified.
@param padding This amount of padding is inserted between widgets.
"""
assert isinstance(content, list) or isinstance(content, tuple)
Widget.__init__(self)
self.align = align
self.padding = padding
self.content = [x or Spacer() for x in content]
self.expandable = []
def _get_controls(self):
"""
Returns Controls within the layout.
"""
controls = []
for item in self.content:
controls += item._get_controls()
return controls
def add(self, item):
"""
Adds a new Widget to the layout.
@param item The Widget to be added
"""
self.content.append(item or Spacer())
self.saved_dialog.set_needs_layout()
def delete(self):
"""Deletes all graphic elements within the layout."""
for item in self.content:
item.delete()
Widget.delete(self)
def expand(self, width, height):
"""
Expands to fill available vertical space. We split available space
equally between all spacers.
"""
available = int((height - self.height) / len(self.expandable))
remainder = height - self.height - len(self.expandable) * available
for item in self.expandable:
if remainder > 0:
item.expand(item.width, item.height + available + 1)
remainder -= 1
else:
item.expand(item.width, item.height + available)
self.height = height
self.width = width
def is_expandable(self):
"""True if we contain expandable content."""
return len(self.expandable) > 0
def remove(self, item):
"""
Removes a Widget from the layout.
@param item The Widget to be removed
"""
item.delete()
self.content.remove(item)
self.saved_dialog.set_needs_layout()
def layout(self, x, y):
"""
Lays out the child Widgets, in order from top to bottom.
@param x X coordinate of the lower left corner
@param y Y coordinate of the lower left corner
"""
Widget.layout(self, x, y)
# Expand any expandable content to our width
for item in self.content:
if item.is_expandable() and item.width < self.width:
item.expand(self.width, item.height)
top = y + self.height
if self.align == HALIGN_RIGHT:
for item in self.content:
item.layout(x + self.width - item.width,
top - item.height)
top -= item.height + self.padding
elif self.align == HALIGN_CENTER:
for item in self.content:
item.layout(x + self.width/2 - item.width/2,
top - item.height)
top -= item.height + self.padding
else: # HALIGN_LEFT
for item in self.content:
item.layout(x, top - item.height)
top -= item.height + self.padding
def set(self, content):
"""
Sets an entirely new set of Widgets, discarding the old.
@param content The new list of Widgets
"""
self.delete()
self.content = content
self.saved_dialog.set_needs_layout()
def size(self, dialog):
"""
Calculates size of the layout, based on its children.
@param dialog The Dialog which contains the layout
"""
if dialog is None:
return
Widget.size(self, dialog)
if len(self.content) < 2:
height = 0
else:
height = -self.padding
width = 0
for item in self.content:
item.size(dialog)
height += item.height + self.padding
width = max(width, item.width)
self.width, self.height = width, height
self.expandable = [x for x in self.content if x.is_expandable()]
def teardown(self):
for item in self.content:
item.teardown()
self.content = []
Widget.teardown(self)
class HorizontalLayout(VerticalLayout):
"""
Arranges Widgets from left to right.
"""
def __init__(self, content=[], align=VALIGN_CENTER, padding=5):
"""
Creates a new HorizontalLayout.
@param content A list of Widgets to be arranged
@param align VALIGN_TOP if Widgets are to be aligned to the top
VALIGN_CENTER if they should be centered, and
VALIGN_BOTTOM if they should be aligned to the bottom.
@param padding This amount of padding is inserted around the edge
of the widgets and between widgets.
"""
VerticalLayout.__init__(self, content, align, padding)
def expand(self, width, height):
"""
Expands to fill available horizontal space. We split available space
equally between all spacers.
"""
available = int((width - self.width) / len(self.expandable))
remainder = height - self.height - len(self.expandable) * available
for item in self.expandable:
if remainder > 0:
item.expand(item.width + available + 1, item.height)
remainder -= 1
else:
item.expand(item.width + available, item.height)
self.width = width
def layout(self, x, y):
"""
Lays out the child Widgets, in order from left to right.
@param x X coordinate of the lower left corner
@param y Y coordinate of the lower left corner
"""
Widget.layout(self, x, y)
# Expand any expandable content to our height
for item in self.content:
if item.is_expandable() and item.height < self.height:
item.expand(item.width, self.height)
left = x
if self.align == VALIGN_TOP:
for item in self.content:
item.layout(left, y + self.height - item.height)
left += item.width + self.padding
elif self.align == VALIGN_CENTER:
for item in self.content:
item.layout(left, y + self.height/2 - item.height/2)
left += item.width + self.padding
else: # VALIGN_BOTTOM
for item in self.content:
item.layout(left, y)
left += item.width + self.padding
def size(self, dialog):
"""
Calculates size of the layout, based on its children.
@param dialog The Dialog which contains the layout
"""
if dialog is None:
return
Widget.size(self, dialog)
height = 0
if len(self.content) < 2:
width = 0
else:
width = -self.padding
for item in self.content:
item.size(dialog)
height = max(height, item.height)
width += item.width + self.padding
self.width, self.height = width, height
self.expandable = [x for x in self.content if x.is_expandable()]
class GridLayout(Widget):
"""
Arranges Widgets in a table. Each cell's height and width are set to
the maximum width of any Widget in its column, or the maximum height of
any Widget in its row.
Widgets are by default aligned to the top left corner of their cells.
Another anchor point may be specified, i.e. ANCHOR_CENTER will ensure
that Widgets are centered within cells.
"""
def __init__(self, content=[[]], anchor=ANCHOR_TOP_LEFT, padding=5,
offset=(0, 0)):
"""
Defines a new GridLayout.
@param content A list of rows, each of which is a list of cells
within that row. 'None' may be used for empty cells,
and rows do not need to all be the same length.
@param anchor Alignment of
"""
assert ((isinstance(content, list) or isinstance(content, tuple)) and
(len(content) == 0 or (isinstance(content[0], list) or
isinstance(content[0], tuple))))
Widget.__init__(self)
self.content = content
self.anchor = anchor
self.padding = padding
self.offset = offset
self.max_heights = []
self.max_widths = []
def _get_controls(self):
"""
Returns Controls within the layout.
"""
controls = []
for row in self.content:
for cell in row:
if cell is not None:
controls += cell._get_controls()
return controls
def add_row(self, row):
"""
Adds a new row to the layout
@param row An array of widgets, or None for cells without widgets
"""
assert isinstance(row, tuple) or isinstance(row, list)
self.content.append(row)
if self.saved_dialog is not None:
self.saved_dialog.set_needs_layout()
def delete(self):
"""Deletes all graphic elements within the layout."""
for row in self.content:
for cell in row:
cell.delete()
Widget.delete(self)
def delete_row(self, row):
"""
Deletes a row from the layout
@param row Index of row
"""
if len(self.content) <= row:
return
row = self.content.pop(row)
for column in row:
if column is not None:
column.delete()
if self.saved_dialog is not None:
self.saved_dialog.set_needs_layout()
def get(self, column, row):
"""
Returns the widget located at a given column and row, or None.
@param column Column of cell
@param row Row of cell
"""
if row >= len(self.content):
return None
row = self.content[row]
if column >= len(row):
return None
else:
return row[column]
def layout(self, x, y):
"""
Lays out all Widgets within this layout.
@param x X coordinate of lower left corner
@param y Y coordinate of lower left corner
"""
Widget.layout(self, x, y)
row_index = 0
placement = Widget()
placement.y = y + self.height
for row in self.content:
col_index = 0
placement.x = x
placement.height = self.max_heights[row_index]
placement.y -= placement.height
for cell in row:
placement.width = self.max_widths[col_index]
if cell is not None:
if cell.is_expandable():
cell.expand(placement.width, placement.height)
cell.layout(*GetRelativePoint(placement, self.anchor,
cell, self.anchor,
self.offset))
placement.x += placement.width
col_index += 1
row_index += 1
def set(self, column, row, item):
"""
Sets the content of a cell within the grid.
@param column The column of the cell to be set
@param row The row of the cell to be set
@param item The new Widget to be set in that cell
"""
if len(self.content) <= row:
self.content = list(self.content) + \
[] * (row - len(self.content) + 1)
if len(self.content[row]) <= column:
self.content[row] = list(self.content[row]) + \
[None] * (column - len(self.content[row]) + 1)
if self.content[row][column] is not None:
self.content[row][column].delete()
self.content[row][column] = item
self.saved_dialog.set_needs_layout()
def size(self, dialog):
"""Recalculates our size and the maximum widths and heights of
each row and column in our table.
@param dialog The Dialog within which we are contained
"""
if dialog is None:
return
Widget.size(self, dialog)
self.max_heights = [0] * len(self.content)
width = 0
for row in self.content:
width = max(width, len(row))
self.max_widths = [self.padding] * width
row_index = 0
for row in self.content:
max_height = self.padding
col_index = 0
for cell in row:
if cell is not None:
cell.size(dialog)
width, height = cell.width, cell.height
else:
width = height = 0
max_height = max(max_height, height + self.padding)
max_width = self.max_widths[col_index]
max_width = max(max_width, width + self.padding)
self.max_widths[col_index] = max_width
col_index += 1
self.max_heights[row_index] = max_height
row_index += 1
if self.max_widths:
self.width = reduce(lambda x, y: x + y, self.max_widths) \
- self.padding
else:
self.width = 0
if self.max_heights:
self.height = reduce(lambda x, y: x + y, self.max_heights) \
- self.padding
else:
self.height = 0
def teardown(self):
for row in self.content:
for cell in row:
cell.teardown()
self.content = []
Widget.teardown(self)
class FreeLayout(Spacer):
"""
FreeLayout defines a rectangle on the screen where Widgets may be placed
freely, in relation to one of its anchor points. There is no constraints
against the Widgets overlapping.
FreeLayout will expand to fill available space in layouts; thus you could
place a FreeLayout as one half of a VerticalLayout, lay out controls in
the other half, and be assured the FreeLayout would be resized to the
width of the overall Dialog.
"""
def __init__(self, width=0, height=0, content=[]):
"""
Creates a new FreeLayout.
@param width Minimum width of FreeLayout area
@param height Minimum height of FreeLayout area
@param content A list of placement/Widget tuples, in the form:
[(ANCHOR_TOP_LEFT, 0, 0, YourWidget()),
(ANCHOR_TOP_RIGHT, 0, 0, YourWidget()),
(ANCHOR_CENTER, 30, -20, YourWidget())]
where each tuple is (anchor, offset-x, offset-y, widget)
"""
Spacer.__init__(self, width, height)
self.content = content
def _get_controls(self):
"""Returns controls within the FreeLayout"""
controls = []
for anchor, x, y, item in self.content:
controls += item._get_controls()
return controls
def add(self, anchor, x, y, widget):
"""
Adds a new Widget to the FreeLayout.
@param dialog Dialog which contains the FreeLayout
@param anchor Anchor point to set for the widget
@param x X-coordinate of offset from anchor point; positive is to
the right
@param y Y-coordinate of offset from anchor point; positive is upward
@param widget The Widget to be added
"""
self.content.append( (anchor, x, y, widget) )
self.saved_dialog.set_needs_layout()
def layout(self, x, y):
"""
Lays out Widgets within the FreeLayout. We make no attempt to
assure there's enough space for them.
@param x X coordinate of lower left corner
@param y Y coordinate of lower left corner
"""
Spacer.layout(self, x, y)
for anchor, offset_x, offset_y, widget in self.content:
x, y = GetRelativePoint(self, anchor, widget, anchor,
(offset_x, offset_y))
widget.layout(x, y)
def remove(self, dialog, widget):
"""
Removes a widget from the FreeLayout.
@param dialog Dialog which contains the FreeLayout
@param widget The Widget to be removed
"""
self.content = [x for x in self.content if x[3] != widget]
def size(self, dialog):
"""
Calculate size of the FreeLayout and all Widgets inside
@param dialog The Dialog which contains the FreeLayout
"""
if dialog is None:
return
Spacer.size(self, dialog)
for anchor, offset_x, offset_y, widget in self.content:
widget.size(dialog)
def teardown(self):
for _, _, _, item in self.content:
item.teardown()
self.content = []
Widget.teardown(self)
| Python |
# kytten/menu.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import pyglet
from widgets import Widget, Control
from dialog import Dialog
from frame import Frame
from layout import GetRelativePoint, VerticalLayout
from layout import ANCHOR_CENTER, ANCHOR_TOP_LEFT, ANCHOR_BOTTOM_LEFT
from layout import HALIGN_CENTER
from layout import VALIGN_TOP, VALIGN_CENTER, VALIGN_BOTTOM
from override import KyttenLabel
from scrollable import Scrollable
class MenuOption(Control):
"""
MenuOption is a choice within a menu. When selected, it inverts
(inverted color against text-color background) to indicate that it
has been chosen.
"""
def __init__(self, text="", anchor=ANCHOR_CENTER, menu=None,
disabled=False):
Control.__init__(self, disabled=disabled)
self.text = text
self.anchor = anchor
self.menu = menu
self.label = None
self.background = None
self.highlight = None
self.is_selected = False
def delete(self):
if self.label is not None:
self.label.delete()
self.label = None
if self.background is not None:
self.background.delete()
self.background = None
if self.highlight is not None:
self.highlight.delete()
self.highlight = None
def expand(self, width, height):
self.width = width
self.height = height
def is_expandable(self):
return True
def layout(self, x, y):
self.x, self.y = x, y
if self.background is not None:
self.background.update(x, y, self.width, self.height)
if self.highlight is not None:
self.highlight.update(x, y, self.width, self.height)
font = self.label.document.get_font()
height = font.ascent - font.descent
x, y = GetRelativePoint(self, self.anchor,
Widget(self.label.content_width, height),
self.anchor, (0, 0))
self.label.x = x
self.label.y = y - font.descent
def on_gain_highlight(self):
Control.on_gain_highlight(self)
self.size(self.saved_dialog) # to set up the highlight
if self.highlight is not None:
self.highlight.update(self.x, self.y,
self.menu.width, self.height)
def on_lose_highlight(self):
Control.on_lose_highlight(self)
if self.highlight is not None:
self.highlight.delete()
self.highlight = None
def on_mouse_release(self, x, y, button, modifiers):
self.menu.select(self.text)
def select(self):
if self.is_disabled():
return # disabled options can't be selected
self.is_selected = True
if self.label is not None:
self.label.delete()
self.label = None
if self.saved_dialog is not None:
self.saved_dialog.set_needs_layout()
def size(self, dialog):
if dialog is None:
return
Control.size(self, dialog)
if self.is_selected:
path = ['menuoption', 'selection']
else:
path = ['menuoption']
if self.label is None:
if self.is_disabled():
color = dialog.theme[path]['disabled_color']
else:
color = dialog.theme[path]['text_color']
self.label = KyttenLabel(self.text,
color=color,
font_name=dialog.theme[path]['font'],
font_size=dialog.theme[path]['font_size'],
batch=dialog.batch,
group=dialog.fg_group)
font = self.label.document.get_font()
self.width = self.label.content_width
self.height = font.ascent - font.descent
if self.background is None:
if self.is_selected:
self.background = \
dialog.theme[path]['highlight']['image'].generate(
dialog.theme[path]['gui_color'],
dialog.batch,
dialog.bg_group)
if self.highlight is None:
if self.is_highlight():
self.highlight = \
dialog.theme[path]['highlight']['image'].generate(
dialog.theme[path]['highlight_color'],
dialog.batch,
dialog.highlight_group)
def unselect(self):
self.is_selected = False
if self.label is not None:
self.label.delete()
self.label = None
if self.background is not None:
self.background.delete()
self.background = None
if self.saved_dialog is not None:
self.saved_dialog.set_needs_layout()
def teardown(self):
self.menu = None
Control.teardown(self)
class Menu(VerticalLayout):
"""
Menu is a VerticalLayout of MenuOptions. Moving the mouse across
MenuOptions highlights them; clicking one selects it and causes Menu
to send an on_click event.
"""
def __init__(self, options=[], align=HALIGN_CENTER, padding=4,
on_select=None):
self.align = align
menu_options = self._make_options(options)
self.options = dict(zip(options, menu_options))
self.on_select = on_select
self.selected = None
VerticalLayout.__init__(self, menu_options,
align=align, padding=padding)
def _make_options(self, options):
menu_options = []
for option in options:
if option.startswith('-'):
disabled = True
option = option[1:]
else:
disabled = False
menu_options.append(MenuOption(option,
anchor=(VALIGN_CENTER, self.align),
menu=self,
disabled=disabled))
return menu_options
def get_value(self):
return self.selected
def is_input(self):
return True
def select(self, text):
if not text in self.options:
return
if self.selected is not None:
self.options[self.selected].unselect()
self.selected = text
menu_option = self.options[text]
menu_option.select()
if self.on_select is not None:
self.on_select(text)
def set_options(self, options):
self.delete()
self.selected = None
menu_options = self._make_options(options)
self.options = dict(zip(options, menu_options))
self.set(menu_options)
self.saved_dialog.set_needs_layout()
def teardown(self):
self.on_select = None
VerticalLayout.teardown(self)
class Dropdown(Control):
def __init__(self, options=[], selected=None, id=None,
max_height=400, align=VALIGN_TOP, on_select=None,
disabled=False):
assert options
Control.__init__(self, id=id, disabled=disabled)
self.options = options
self.selected = selected or options[0]
assert self.selected in self.options
self.max_height = max_height
self.align = align
self.on_select = on_select
self.field = None
self.label = None
self.pulldown_menu = None
def _delete_pulldown_menu(self):
if self.pulldown_menu is not None:
self.pulldown_menu.window.remove_handlers(self.pulldown_menu)
self.pulldown_menu.teardown()
self.pulldown_menu = None
def delete(self):
if self.field is not None:
self.field.delete()
self.field = None
if self.label is not None:
self.label.delete()
self.label = None
self._delete_pulldown_menu()
def get_value(self):
return self.selected
def is_input(self):
return True
def on_mouse_release(self, x, y, button, modifiers):
if self.is_disabled():
return
if self.pulldown_menu is not None:
self._delete_pulldown_menu() # if it's already up, close it
return
# Setup some callbacks for the dialog
root = self.saved_dialog.get_root()
def on_escape(dialog):
self._delete_pulldown_menu()
def on_select(choice):
self.selected = choice
if self.label is not None:
self.label.delete()
self.label = None
self._delete_pulldown_menu()
self.saved_dialog.set_needs_layout()
if self.on_select is not None:
if self.id is not None:
self.on_select(self.id, choice)
else:
self.on_select(choice)
# We'll need the root window to get window size
width, height = root.window.get_size()
# Calculate the anchor point and location for the dialog
if self.align == VALIGN_TOP:
# Dropdown is at the top, pulldown appears below it
anchor = ANCHOR_TOP_LEFT
x = self.x
y = -(height - self.y - 1)
else:
# Dropdown is at the bottom, pulldown appears above it
anchor = ANCHOR_BOTTOM_LEFT
x = self.x
y = self.y + self.height + 1
# Now to setup the dialog
self.pulldown_menu = Dialog(
Frame(
Scrollable(Menu(options=self.options, on_select=on_select),
height=self.max_height),
path=['dropdown', 'pulldown']
),
window=root.window, batch=root.batch,
group=root.root_group.parent, theme=root.theme,
movable=False, anchor=anchor, offset=(x, y),
on_escape=on_escape)
root.window.push_handlers(self.pulldown_menu)
def layout(self, x, y):
Control.layout(self, x, y)
self.field.update(x, y, self.width, self.height)
x, y, width, height = self.field.get_content_region()
font = self.label.document.get_font()
height = font.ascent - font.descent
self.label.x = x
self.label.y = y - font.descent
def set_options(self, options, selected=None):
self.delete()
self.options = options
self.selected = selected or self.options[0]
self.saved_dialog.set_needs_layout()
def size(self, dialog):
if dialog is None:
return
Control.size(self, dialog)
if self.is_disabled():
color = dialog.theme['dropdown']['disabled_color']
else:
color = dialog.theme['dropdown']['gui_color']
if self.field is None:
self.field = dialog.theme['dropdown']['image'].generate(
color,
dialog.batch, dialog.bg_group)
if self.label is None:
self.label = KyttenLabel(self.selected,
font_name=dialog.theme['dropdown']['font'],
font_size=dialog.theme['dropdown']['font_size'],
color=dialog.theme['dropdown']['text_color'],
batch=dialog.batch, group=dialog.fg_group)
font = self.label.document.get_font()
height = font.ascent - font.descent
self.width, self.height = self.field.get_needed_size(
self.label.content_width, height)
def teardown(self):
self.on_select = False
self._delete_pulldown_menu()
Control.teardown(self)
| Python |
# kytten/file_dialogs.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import glob
import os
import pyglet
from pyglet import gl
from button import Button
from dialog import Dialog
from frame import Frame, SectionHeader
from layout import VerticalLayout, HorizontalLayout
from layout import ANCHOR_CENTER, HALIGN_LEFT, VALIGN_BOTTOM
from menu import Menu, Dropdown
from scrollable import Scrollable
from text_input import Input
from widgets import Label
class FileLoadDialog(Dialog):
def __init__(self, path=os.getcwd(), extensions=[], title="Select File",
width=540, height=300, window=None, batch=None, group=None,
anchor=ANCHOR_CENTER, offset=(0, 0),
theme=None, movable=True, on_select=None, on_escape=None):
self.path = path
self.extensions = extensions
self.title = title
self.on_select = on_select
self.selected_file = None
self._set_files()
def on_parent_menu_select(choice):
self._select_file(self.parents_dict[choice])
def on_menu_select(choice):
self._select_file(self.files_dict[choice])
self.dropdown = Dropdown(options=self.parents,
selected=self.parents[-1],
align=VALIGN_BOTTOM,
on_select=on_parent_menu_select)
self.menu = Menu(options=self.files, align=HALIGN_LEFT,
on_select=on_menu_select)
self.scrollable = Scrollable(
VerticalLayout([self.dropdown, self.menu], align=HALIGN_LEFT),
width=width, height=height)
content = self._get_content()
Dialog.__init__(self, content, window=window, batch=batch, group=group,
anchor=anchor, offset=offset, theme=theme,
movable=movable, on_escape=on_escape)
def _get_content(self):
return Frame(
VerticalLayout([
SectionHeader(self.title),
self.scrollable,
], align=HALIGN_LEFT)
)
def _select_file(self, filename):
if os.path.isdir(filename):
self.path = filename
self._set_files()
self.dropdown.set_options(self.parents,
selected=self.parents[-1])
self.menu.set_options(self.files)
else:
self.selected_file = filename
if self.on_select is not None:
self.on_select(filename)
def _set_files(self):
# Once we have a new path, update our files
filenames = glob.glob(os.path.join(self.path, '*'))
# First, a list of directories
self.parents = []
self.parents_dict = {}
path = self.path
index = 1
while 1:
name = "%d %s" % (index, os.path.basename(path) or path)
self.parents_dict[name] = path
self.parents.append(name)
index += 1
path, child = os.path.split(path)
if not child:
break
self.parents.reverse()
files = [("%s (dir)" % os.path.basename(x), x) for x in filenames
if os.path.isdir(x)]
# Now add the files that match the extensions
if self.extensions:
for filename in filenames:
if os.path.isfile(filename):
ext = os.path.splitext(filename)[1]
if ext in self.extensions:
files.append((os.path.basename(filename), filename))
else:
files.extend([(os.path.basename(x), x) for x in filenames
if os.path.isfile(x)])
self.selected_file = None
self.files_dict = dict(files)
self.files = self.files_dict.keys()
def dir_sort(x, y):
if x.endswith(' (dir)') and y.endswith(' (dir)'):
return cmp(x, y)
elif x.endswith(' (dir)'):
return -1
elif y.endswith(' (dir)'):
return 1
else:
return cmp(x, y)
self.files.sort(dir_sort)
def get(self):
return self.selected_file
def size(self, dialog):
Dialog.size(self, dialog)
def teardown(self):
self.on_select = None
Dialog.teardown(self)
class FileSaveDialog(FileLoadDialog):
def __init__(self, *args, **kwargs):
self.text_input = Input()
# Set up buttons to be shown in our contents
def on_save():
self._do_select()
self.save_button = Button("Save", on_click=on_save)
def on_cancel():
self._do_cancel()
self.cancel_button = Button("Cancel", on_click=on_cancel)
FileLoadDialog.__init__(self, *args, **kwargs)
# Setup our event handlers
def on_enter(dialog):
self._do_select()
self.on_enter = on_enter
self.real_on_select = self.on_select
def on_select(filename):
self.text_input.set_text(filename)
self.on_select = on_select
def _do_cancel(self):
if self.on_escape is not None:
self.on_escape(self)
else:
self.delete()
self.window.remove_handlers(self)
def _do_select(self):
filename = self.text_input.get_text()
path, base = os.path.split(filename)
if not base:
filename = None
elif not path:
filename = os.path.join(self.path, filename)
if self.real_on_select is not None:
if self.id is not None:
self.real_on_select(self.id, filename)
else:
self.real_on_select(filename)
def _get_content(self):
return Frame(
VerticalLayout([
SectionHeader(self.title),
self.scrollable,
Label("Filename:"),
self.text_input,
HorizontalLayout([
self.save_button, None, self.cancel_button
]),
], align=HALIGN_LEFT)
)
class DirectorySelectDialog(FileLoadDialog):
def __init__(self, *args, **kwargs):
self.text_input = Input()
# Set up buttons to be shown in our contents
def on_select_button():
self._do_select()
self.select_button = Button("Select", on_click=on_select_button)
def on_cancel_button():
self._do_cancel()
self.cancel_button = Button("Cancel", on_click=on_cancel_button)
FileLoadDialog.__init__(self, *args, **kwargs)
# Setup our event handlers
def on_enter(dialog):
self._do_select()
self.on_enter = on_enter
self.real_on_select = self.on_select
def on_select(filename):
self.text_input.set_text(filename)
self.on_select = on_select
def on_parent_menu_select(choice):
self.text_input.set_text(self.parents_dict[choice])
self._do_open()
self.dropdown.on_select = on_parent_menu_select
def _do_cancel(self):
if self.on_escape is not None:
self.on_escape(self)
else:
self.delete()
self.window.remove_handlers(self)
def _do_open(self):
filename = self.text_input.get_text()
if os.path.isdir(filename):
self.path = filename
self._set_files()
self.dropdown.set_options(self.parents,
selected=self.parents[-1])
self.menu.set_options(self.files)
def _do_select(self):
filename = self.text_input.get_text()
path, base = os.path.split(filename)
if not base:
filename = None
elif not path:
filename = os.path.join(self.path, filename)
if self.real_on_select is not None:
if self.id is not None:
self.real_on_select(self.id, filename)
else:
self.real_on_select(filename)
def _get_content(self):
return Frame(
VerticalLayout([
SectionHeader(self.title),
self.scrollable,
Label("Directory:"),
self.text_input,
HorizontalLayout([
self.select_button, None, self.cancel_button
]),
], align=HALIGN_LEFT)
)
def _select_file(self, filename):
if not os.path.isdir(filename):
return # we accept only directories!
if self.selected_file == filename:
if filename != self.path:
self._do_open()
else:
self._do_select()
else:
self.selected_file = filename
if self.on_select is not None:
self.on_select(filename)
def _set_files(self):
# Once we have a new path, update our files
filenames = glob.glob(os.path.join(self.path, '*'))
# First, a list of directories
self.parents = []
self.parents_dict = {}
path = self.path
index = 1
while 1:
name = "%d %s" % (index, os.path.basename(path) or path)
self.parents_dict[name] = path
self.parents.append(name)
index += 1
path, child = os.path.split(path)
if not child:
break
self.parents.reverse()
files = [('(this dir)', self.path)] + \
[("%s (dir)" % os.path.basename(x), x) for x in filenames
if os.path.isdir(x)]
# Now add the files that match the extensions
if self.extensions:
for filename in filenames:
if os.path.isfile(filename):
ext = os.path.splitext(filename)[1]
if ext in self.extensions:
files.append(('-%s' % os.path.basename(filename),
filename))
else:
files.extend([('-%s' % os.path.basename(x), x) for x in filenames
if os.path.isfile(x)])
self.selected_file = None
self.files_dict = dict(files)
self.files = self.files_dict.keys()
def dir_sort(x, y):
if x == '(this dir)':
return -1
elif x.endswith(' (dir)') and y.endswith(' (dir)'):
return cmp(x, y)
elif x.endswith(' (dir)') and y != '(this dir)':
return -1
elif y.endswith(' (dir)'):
return 1
else:
return cmp(x, y)
self.files.sort(dir_sort)
| Python |
# kytten/scrollbar.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import pyglet
from widgets import Control
class HScrollbar(Control):
"""
A horizontal scrollbar. Position is measured from 0.0 to 1.0, and bar
size is set as a percentage of the maximum.
"""
IMAGE_LEFT = ['hscrollbar', 'left']
IMAGE_SPACE = ['hscrollbar', 'space']
IMAGE_BAR = ['hscrollbar', 'bar']
IMAGE_RIGHT = ['hscrollbar', 'right']
IMAGE_LEFTMAX = ['hscrollbar', 'leftmax']
IMAGE_RIGHTMAX = ['hscrollbar', 'rightmax']
def __init__(self, width):
"""
Creates a new scrollbar.
@param width Width of the area for which we are a scrollbar
"""
Control.__init__(self, width=width, height=0)
self.__init2__(width)
def __init2__(self, width):
"""
HScrollbar and VScrollbar share similiar data structures, which this
function initializes.
@param width Width of the area for which we are a scrollbar
"""
self.left = None
self.space = None
self.right = None
self.bar = None
self.pos = 0.0
self.bar_width = 0.5
self.is_dragging = False
self.is_scrolling = False
self.scroll_delta = 0
def _get_left_region(self):
"""
Return area of the left button (x, y, width, height)
"""
if self.left is not None:
return self.x, self.y, self.left.width, self.height
else:
return self.x, self.y, 0, 0
def _get_right_region(self):
"""
Return area of the right button (x, y, width, height)
"""
if self.right is not None:
return (self.x + self.width - self.right.width, self.y,
self.right.width, self.height)
else:
return self.x + self.width, self.y, 0, 0
def _get_space_region(self):
"""
Return area of the space in which the bar moves
(x, y, width, height)
"""
if self.left is not None and self.right is not None:
return (self.x + self.left.width, self.y,
self.width - self.left.width - self.right.width,
self.height)
else:
return self.x, self.y, self.width, self.height
def _get_bar_region(self):
"""
Return area of the bar within the scrollbar (x, y, width, height)
"""
if self.left is not None and self.right is not None:
left_width = self.left.width
right_width = self.right.width
else:
left_width = right_width = 0
self.pos = max(min(self.pos, 1.0 - self.bar_width), 0.0)
space_width = self.width - left_width - right_width
return (int(self.x + left_width + self.pos * space_width),
self.y,
int(self.bar_width * space_width),
self.height)
def delete(self):
"""
Delete all graphic elements used by the scrollbar
"""
if self.left is not None:
self.left.delete()
self.left = None
if self.space is not None:
self.space.delete()
self.space = None
if self.bar is not None:
self.bar.delete()
self.bar = None
if self.right is not None:
self.right.delete()
self.right = None
def drag_bar(self, dx, dy):
"""
Drag the bar, keeping it within limits
@param dx Delta X
@param dy Delta Y
"""
_, _, space_width, space_height = self._get_space_region()
_, _, bar_width, bar_height = self._get_bar_region()
self.pos = min(max(self.pos + float(dx) / space_width, 0.0),
1.0 - float(bar_width)/space_width)
def ensure_visible(self, left, right, max_width):
"""
Ensure that the area of space between left and right is completely
visible.
@param left Left end of the space
@param right Right end of the space
@param max_width Maximum width of space
"""
pos_x = self.pos * max_width
pos_width = self.bar_width * max_width
if pos_x <= left and pos_x + pos_width > right:
return # We're fine
elif pos_x > left:
self.pos = pos_x / max_width # Shift to the left
elif pos_x + pos_width < right:
self.pos = (right - pos_width) / max_width # Shift to the right
self.pos = min(max(self.pos, 0.0), 1.0 - self.bar_width)
self.delete()
self.saved_dialog.set_needs_layout()
def get(self, width, max_width):
"""
Returns the position of the bar, in pixels from the controlled area's
left edge
"""
return int(self.pos * max_width)
def layout(self, x, y):
"""
Lays out the scrollbar components
@param x X coordinate of lower left corner
@param y Y coordinate of lower left corner
"""
self.x, self.y = x, y
if self.left is not None:
self.left.update(*self._get_left_region())
if self.right is not None:
self.right.update(*self._get_right_region())
if self.space is not None:
self.space.update(*self._get_space_region())
if self.bar is not None:
self.bar.update(*self._get_bar_region())
def on_gain_focus(self):
if self.saved_dialog is not None:
self.saved_dialog.set_wheel_target(self)
def on_lose_focus(self):
if self.saved_dialog is not None:
self.saved_dialog.set_wheel_target(None)
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
"""
We drag the bar only if the user had previously clicked on the bar
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param dx Delta X
@param dy Delta Y
@param buttons Buttons held while dragging
@param modifiers Modifiers to apply to buttons
"""
if self.is_dragging:
self.drag_bar(dx, dy)
self.delete()
self.saved_dialog.set_needs_layout()
return pyglet.event.EVENT_HANDLED
def on_mouse_press(self, x, y, button, modifiers):
"""
If the mouse press falls within the space, move the bar over to the
mouse. Otherwise, activate scrolling.
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param button Button being pressed
@param modifiers Modifiers to apply to button
"""
space_x, space_y, space_width, space_height = self._get_space_region()
if x >= space_x and x < space_x + space_width and \
y >= space_y and y < space_y + space_height:
self.set_bar_pos(x, y)
self.is_dragging = True
self.delete()
self.saved_dialog.set_needs_layout()
else:
left_x, left_y, left_width, left_height = self._get_left_region()
if x >= left_x and x < left_x + left_width and \
y >= left_y and y < left_y + left_height:
self.is_scrolling = True
self.scroll_delta = -1
else:
right_x, right_y, right_width, right_height = \
self._get_right_region()
if x >= right_x and x < right_x + right_width and \
y >= right_y and y < right_y + right_height:
self.is_scrolling = True
self.scroll_delta = 1
def on_mouse_release(self, x, y, button, modifiers):
"""
Cancels dragging or scrolling
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param button Button being released
@param modifiers Modifiers to apply to button
"""
self.is_dragging = False
self.is_scrolling = False
self.scroll_delta = 0
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
"""
Mousewheel was moved some number of clicks
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param scroll_x Number of clicks horizontally mouse was moved
@param scroll_y Number of clicks vertically mouse was moved
"""
self.drag_bar(scroll_y * 10, 0)
self.delete()
self.saved_dialog.set_needs_layout()
def on_update(self, dt):
"""
When scrolling, we increment our position each update
@param dt Time delta, in seconds
"""
if self.is_scrolling:
self.drag_bar(self.scroll_delta * 50.0 * dt, 0)
self.saved_dialog.set_needs_layout()
def set(self, width, max_width):
"""
Sets the width of the scrollbar
@param width Width the scrollbar occupies
@param max_width Maximum width of the scrollable area
"""
self.width = width
self.bar_width = max(float(width) / max_width, 0.0)
self.pos = min(self.pos, 1.0 - self.bar_width)
def set_bar_pos(self, x, y):
"""
When the mouse is pressed within scrollbar space, move the bar over
underneath it.
@param x X coordinate of mouse press
@param y Y coordinate of mouse press
"""
space_x, space_y, space_width, space_height = self._get_space_region()
bar_x, bar_y, bar_width, bar_height = self._get_bar_region()
if x < bar_x:
self.pos = float(x - space_x) / space_width
elif x > bar_x + bar_width:
max_bar_x = space_width - bar_width
x -= bar_width
self.pos = float(min(max_bar_x, x - space_x)) / space_width
if self.bar is not None:
self.bar.update(*self._get_bar_region())
def size(self, dialog):
"""
Creates scrollbar components.
"""
if dialog is None:
return
Control.size(self, dialog)
dialog.set_wheel_hint(self)
if self.left is None:
if self.pos > 0.0:
path = self.IMAGE_LEFT
else:
path = self.IMAGE_LEFTMAX
self.left = dialog.theme[path]['image'].generate(
dialog.theme[path]['gui_color'],
dialog.batch, dialog.fg_group)
# Left button is our basis for minimum dimension
self.width, self.height = self.left.width, self.left.height
if self.space is None:
path = self.IMAGE_SPACE
self.space = dialog.theme[path]['image'].generate(
dialog.theme[path]['gui_color'],
dialog.batch, dialog.fg_group)
if self.bar is None:
path = self.IMAGE_BAR
self.bar = dialog.theme[path]['image'].generate(
dialog.theme[path]['gui_color'],
dialog.batch, dialog.fg_group)
if self.right is None:
if self.pos < 1.0 - self.bar_width:
path = self.IMAGE_RIGHT
else:
path = self.IMAGE_RIGHTMAX
self.right = dialog.theme[path]['image'].generate(
dialog.theme[path]['gui_color'],
dialog.batch, dialog.fg_group)
class VScrollbar(HScrollbar):
"""
A vertical scrollbar. Position is measured from 0.0 to 1.0, and bar size
is set as a percentage of the maximum. Note that left is top, and
right is bottom, from the viewpoint of the VScrollbar.
"""
IMAGE_LEFT = ['vscrollbar', 'up']
IMAGE_SPACE = ['vscrollbar', 'space']
IMAGE_BAR = ['vscrollbar', 'bar']
IMAGE_RIGHT = ['vscrollbar', 'down']
IMAGE_LEFTMAX = ['vscrollbar', 'upmax']
IMAGE_RIGHTMAX = ['vscrollbar', 'downmax']
def __init__(self, height):
"""
Creates a new scrollbar. At the outset, we are presented with maximum
height and the templates to use.
@param height Height of the area for which we are a scrollbar
"""
Control.__init__(self, width=0, height=height)
self.__init2__(height)
def _get_left_region(self):
"""Returns the area occupied by the up button
(x, y, width, height)"""
if self.left is not None:
return (self.x, self.y + self.height - self.left.height,
self.width, self.left.height)
else:
return self.x, self.y, 0, 0
def _get_right_region(self):
"""Returns the area occupied by the down button
(x, y, width, height)"""
if self.right is not None:
return self.x, self.y, self.width, self.right.height
else:
return self.x, self.y, 0, 0
def _get_space_region(self):
"""Returns the area occupied by the space between up and down
buttons (x, y, width, height)"""
if self.left is not None and self.right is not None:
return (self.x,
self.y + self.right.height,
self.width,
self.height - self.left.width - self.right.width)
else:
return self.x, self.y, self.width, self.height
def _get_bar_region(self):
"""Returns the area occupied by the bar (x, y, width, height)"""
if self.left is not None and self.right is not None:
left_height = self.left.height
right_height = self.right.height
else:
left_height = right_height = 0
self.pos = max(min(self.pos, 1.0 - self.bar_width), 0.0)
space_height = self.height - left_height - right_height
top = self.y + self.height - left_height
return (self.x, int(top - (self.pos + self.bar_width) * space_height),
self.width, int(self.bar_width * space_height))
def drag_bar(self, dx, dy):
"""Handles dragging the bar.
@param dx Delta X
@param dy Delta Y
"""
_, _, space_width, space_height = self._get_space_region()
_, _, bar_width, bar_height = self._get_bar_region()
self.pos = min(max(self.pos - float(dy) / space_height, 0.0),
1.0 - float(bar_height)/space_height)
def ensure_visible(self, top, bottom, max_height):
"""
Ensure that the area of space between top and bottom is completely
visible.
@param top Top end of the space
@param bottom Bottom end of the space
@param max_height Maximum height of space
"""
bar_top = (1.0 - self.pos) * max_height
bar_bottom = bar_top - self.bar_width * max_height
if bar_top > top and bar_bottom <= bottom:
return # We're fine
elif bar_top < top:
# Shift upward
self.pos = 1.0 - float(top) / max_height
elif bar_bottom > bottom:
# Shift downward
self.pos = 1.0 - float(bottom) / max_height - self.bar_width
self.pos = min(max(self.pos, 0.0), 1.0 - self.bar_width)
self.delete()
self.saved_dialog.set_needs_layout()
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
"""
Mousewheel was moved some number of clicks
@param x X coordinate of mouse
@param y Y coordinate of mouse
@param scroll_x Number of clicks horizontally mouse was moved
@param scroll_y Number of clicks vertically mouse was moved
"""
self.drag_bar(0, scroll_y * 10)
self.delete()
self.saved_dialog.set_needs_layout()
def on_update(self, dt):
"""
When scrolling, we increment our position each update
@param dialog Dialog in which we're contained
@param dt Time delta, in seconds
"""
if self.is_scrolling:
self.drag_bar(0, -self.scroll_delta * 50.0 * dt)
self.saved_dialog.set_needs_layout()
def set(self, height, max_height):
"""Sets the new height of the scrollbar, and the height of
the bar relative to the scrollable area.
@param height Scrollable region height
@param max_height Maximum scrollable height
"""
self.height = height
self.bar_width = max(float(height) / max_height, 0.0)
self.pos = min(self.pos, 1.0 - self.bar_width)
def set_bar_pos(self, x, y):
"""Sets the scrollbar position. Moves the scrollbar to intercept
the mouse if it is not already in place."""
space_x, space_y, space_width, space_height = self._get_space_region()
bar_x, bar_y, bar_width, bar_height = self._get_bar_region()
top = space_y + space_height
if y > bar_y + bar_height:
self.pos = float(top - y) / space_height
elif y < bar_y:
y += bar_height
max_bar_y = space_height - bar_height
self.pos = float(min(max_bar_y, top - y)) / space_height
if self.bar is not None:
self.bar.update(*self._get_bar_region())
| Python |
# kytten/slider.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import pyglet
from widgets import Control
class Slider(Control):
"""
A horizontal slider. Position is measured from 0.0 to 1.0.
"""
IMAGE_BAR = ['slider', 'bar']
IMAGE_KNOB = ['slider', 'knob']
IMAGE_STEP = ['slider', 'step']
def __init__(self, value=0.0, min_value=0.0, max_value=1.0, steps=None,
width=100, id=None, on_set=None, disabled=False):
"""
Creates a new slider.
@param min_value Minimum value
@param max_value Maximum value
@param steps None if this slider should cover the range from 0.0 to
1.0 smoothly, otherwise we will divide the range
up into steps. For instance, 2 steps would give the
possible values 0, 0.5, and 1.0 (then multiplied by scale)
@param width Minimum width of the tracking area. Note that this
is the interior length of the slider, not the overall
size.
@param id ID for identifying this slider.
@param on_set Callback function for when the value of this slider
changes.
@param diasbled True if the slider should be disabled
"""
Control.__init__(self, id=id, disabled=disabled)
self.min_value = min_value
self.max_value = max_value
self.steps = steps
self.min_width = width
self.on_set = on_set
self.bar = None
self.knob = None
self.markers = []
self.pos = max(
min(float(value - min_value) / (max_value - min_value), 1.0),
0.0)
self.offset = (0, 0)
self.step_offset = (0, 0)
self.padding = (0, 0, 0, 0)
self.is_dragging = False
def delete(self):
"""
Delete all graphic elements used by the slider
"""
if self.bar is not None:
self.bar.delete()
self.bar = None
if self.knob is not None:
self.knob.delete()
self.knob = None
for marker in self.markers:
marker.delete()
self.markers = []
def expand(self, width, height):
self.width = width
def get_value(self):
return self.min_value + (self.max_value - self.min_value) * self.pos
def is_expandable(self):
return True
def is_input(self):
return True
def layout(self, x, y):
"""
Lays out the slider components
@param x X coordinate of lower left corner
@param y Y coordinate of lower left corner
"""
self.x, self.y = x, y
if self.bar is not None:
left, right, top, bottom = self.padding
self.bar.update(x + left, y + bottom,
self.width - left - right,
self.height - top - bottom)
x, y, width, height = self.bar.get_content_region()
if self.knob is not None:
offset_x, offset_y = self.offset
self.knob.update(x + int(width * self.pos) + offset_x,
y + offset_y,
self.knob.width, self.knob.height)
if self.markers:
step = float(width) / self.steps
offset_x, offset_y = self.step_offset
for n in xrange(0, self.steps + 1):
self.markers[n].update(int(x + step * n) + offset_x,
y + offset_y,
self.markers[n].width,
self.markers[n].height)
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
if self.is_dragging and self.bar is not None:
bar_x, bar_y, bar_width, bar_height = self.bar.get_content_region()
self.set_pos(self.pos + float(dx) / bar_width)
def on_mouse_press(self, x, y, button, modifiers):
if self.is_disabled():
return
self.is_dragging = True
if self.bar is not None:
bar_x, bar_y, bar_width, bar_height = self.bar.get_content_region()
self.set_pos(float(x - bar_x) / bar_width)
def on_mouse_release(self, x, y, button, modifiers):
if self.is_disabled():
return
self.is_dragging = False
self.snap_to_nearest()
if self.on_set is not None:
value = self.get_value()
if self.id is not None:
self.on_set(self.id, value)
else:
self.on_set(value)
def set_pos(self, pos):
self.pos = max(min(pos, 1.0), 0.0)
if self.bar is not None and self.knob is not None:
x, y, width, height = self.bar.get_content_region()
offset_x, offset_y = self.offset
self.knob.update(x + int(width * self.pos) + offset_x,
y + offset_y,
self.knob.width, self.knob.height)
def size(self, dialog):
"""
Creates slider components.
"""
if dialog is None:
return
Control.size(self, dialog)
if self.is_disabled():
color = dialog.theme['slider']['disabled_color']
else:
color = dialog.theme['slider']['gui_color']
if self.bar is None:
path = self.IMAGE_BAR
self.bar = dialog.theme[path]['image'].generate(
color,
dialog.batch, dialog.bg_group)
self.padding = dialog.theme[path]['padding']
if self.knob is None:
path = self.IMAGE_KNOB
self.knob = dialog.theme[path]['image'].generate(
color,
dialog.batch, dialog.highlight_group)
self.offset = dialog.theme[path]['offset']
if not self.markers and self.steps is not None:
path = self.IMAGE_STEP
for n in xrange(0, self.steps + 1):
self.markers.append(
dialog.theme[path]['image'].generate(
color,
dialog.batch, dialog.fg_group))
self.step_offset = dialog.theme[path]['offset']
width, height = self.bar.get_needed_size(self.min_width, 0)
left, right, top, bottom = self.padding
self.width = width + left + right
self.height = height + top + bottom
def snap_to_nearest(self):
if self.steps is not None:
n = int(self.pos * self.steps + 0.5)
self.set_pos(float(n) / self.steps)
def teardown(self):
self.on_set = None
Control.teardown(self) | Python |
# kytten/frame.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
# Classes which wrap one Widget.
# Wrapper: a base class for Widgets which contain one other Widget.
# Frame: positions its contained Widget within a graphic, which it stretches
# to cover the Widget's area, or the space within which it is contained.
# TitleFrame: like Frame, but has a title region on top as well.
from widgets import Widget, Control, Graphic, Label
from layout import HorizontalLayout, VerticalLayout, GetRelativePoint
from layout import VALIGN_BOTTOM, HALIGN_LEFT, HALIGN_CENTER, HALIGN_RIGHT
from layout import ANCHOR_CENTER
class Wrapper(Widget):
"""
Wrapper is simply a wrapper around a widget. While the default
Wrapper does nothing more interesting, subclasses might decorate the
widget in some fashion, i.e. Panel might place the widget onto a
panel, or Scrollable might provide scrollbars to let the widget
be panned about within its display area.
"""
def __init__(self, content=None,
is_expandable=False, anchor=ANCHOR_CENTER, offset=(0, 0)):
"""
Creates a new Wrapper around an included Widget.
@param content The Widget to be wrapped.
"""
Widget.__init__(self)
self.content = content
self.expandable = is_expandable
self.anchor = anchor
self.content_offset = offset
def _get_controls(self):
"""Returns Controls contained by the Wrapper."""
return self.content._get_controls()
def delete(self):
"""Deletes graphic elements within the Wrapper."""
if self.content is not None:
self.content.delete()
Widget.delete(self)
def expand(self, width, height):
if self.content.is_expandable():
self.content.expand(width, height)
self.width = width
self.height = height
def is_expandable(self):
return self.expandable
def layout(self, x, y):
"""
Assigns a new position to the Wrapper.
@param x X coordinate of the Wrapper's lower left corner
@param y Y coordinate of the Wrapper's lower left corner
"""
Widget.layout(self, x, y)
if self.content is not None:
x, y = GetRelativePoint(
self, self.anchor,
self.content, self.anchor, self.content_offset)
self.content.layout(x, y)
def set(self, dialog, content):
"""
Sets a new Widget to be contained in the Wrapper.
@param dialog The Dialog which contains the Wrapper
@param content The new Widget to be wrapped
"""
if self.content is not None:
self.content.delete()
self.content = content
dialog.set_needs_layout()
def size(self, dialog):
"""
The default Wrapper wraps up its Widget snugly.
@param dialog The Dialog which contains the Wrapper
"""
if dialog is None:
return
Widget.size(self, dialog)
if self.content is not None:
self.content.size(dialog)
self.width, self.height = self.content.width, self.content.height
else:
self.width = self.height = 0
def teardown(self):
self.content.teardown()
self.content = None
Widget.teardown(self)
class Frame(Wrapper):
"""
Frame draws an untitled frame which encloses the dialog's content.
"""
def __init__(self, content=None, path=['frame'], image_name='image',
is_expandable=False, anchor=ANCHOR_CENTER,
use_bg_group=False):
"""
Creates a new Frame surrounding a widget or layout.
"""
Wrapper.__init__(self, content,
is_expandable=is_expandable, anchor=anchor)
self.frame = None
self.path = path
self.image_name = image_name
self.use_bg_group = use_bg_group
def delete(self):
"""
Removes the Frame's graphical elements.
"""
if self.frame is not None:
self.frame.delete()
self.frame = None
Wrapper.delete(self)
def expand(self, width, height):
if self.content.is_expandable():
content_width, content_height = \
self.frame.get_content_size(width, height)
self.content.expand(content_width, content_height)
self.width, self.height = width, height
def layout(self, x, y):
"""
Positions the Frame.
@param x X coordinate of lower left corner
@param y Y coordinate of lower left corner
"""
self.x, self.y = x, y
self.frame.update(x, y, self.width, self.height)
# In some cases the frame graphic element may allocate more space for
# the content than the content actually fills, due to repeating
# texture constraints. Always center the content.
x, y, width, height = self.frame.get_content_region()
interior = Widget(width, height)
interior.x, interior.y = x, y
x, y = GetRelativePoint(interior, self.anchor,
self.content, self.anchor, self.content_offset)
self.content.layout(x, y)
def size(self, dialog):
"""
Determine minimum size of the Frame.
@param dialog Dialog which contains the Frame
"""
if dialog is None:
return
Wrapper.size(self, dialog)
if self.frame is None:
if self.use_bg_group:
group = dialog.bg_group
else:
group = dialog.panel_group
template = dialog.theme[self.path][self.image_name]
self.frame = template.generate(
dialog.theme[self.path]['gui_color'],
dialog.batch,
group)
self.width, self.height = self.frame.get_needed_size(
self.content.width, self.content.height)
class TitleFrame(VerticalLayout):
def __init__(self, title, content):
VerticalLayout.__init__(self, content=[
HorizontalLayout([
Graphic(path=["titlebar", "left"], is_expandable=True),
Frame(Label(title, path=["titlebar"]),
path=["titlebar", "center"]),
Graphic(path=["titlebar", "right"], is_expandable=True),
], align=VALIGN_BOTTOM, padding=0),
Frame(content, path=["titlebar", "frame"], is_expandable=True),
], padding=0)
class SectionHeader(HorizontalLayout):
def __init__(self, title, align=HALIGN_CENTER):
if align == HALIGN_LEFT:
left_expand = False
right_expand = True
elif align == HALIGN_CENTER:
left_expand = True
right_expand = True
else: # HALIGN_RIGHT
left_expand = True
right_expand = False
HorizontalLayout.__init__(self, content=[
Graphic(path=["section", "left"], is_expandable=left_expand),
Frame(Label(title, path=["section"]),
path=['section', 'center'],
use_bg_group=True),
Graphic(path=["section", "right"], is_expandable=right_expand),
], align=VALIGN_BOTTOM, padding=0)
class FoldingSection(Control, VerticalLayout):
def __init__(self, title, content=None, is_open=True, align=HALIGN_CENTER):
Control.__init__(self)
if align == HALIGN_LEFT:
left_expand = False
right_expand = True
elif align == HALIGN_CENTER:
left_expand = True
right_expand = True
else: # HALIGN_RIGHT
left_expand = True
right_expand = False
self.is_open = is_open
self.folding_content = content
self.book = Graphic(self._get_image_path())
self.header = HorizontalLayout([
Graphic(path=["section", "left"], is_expandable=left_expand),
Frame(HorizontalLayout([
self.book,
Label(title, path=["section"]),
]), path=["section", "center"],
use_bg_group=True),
Graphic(path=["section", "right"], is_expandable=right_expand),
], align=VALIGN_BOTTOM, padding=0)
layout = [self.header]
if self.is_open:
layout.append(content)
VerticalLayout.__init__(self, content=layout, align=align)
def _get_controls(self):
return VerticalLayout._get_controls(self) + \
[(self, self.header.x, self.header.x + self.header.width,
self.header.y + self.header.height, self.header.y)]
def _get_image_path(self):
if self.is_open:
return ["section", "opened"]
else:
return ["section", "closed"]
def hit_test(self, x, y):
return self.header.hit_test(x, y)
def on_mouse_press(self, x, y, button, modifiers):
self.is_open = not self.is_open
self.book.delete()
self.book.path = self._get_image_path()
if self.is_open:
self.add(self.folding_content)
else:
self.remove(self.folding_content)
self.folding_content.delete()
def teardown(self):
self.folding_content.teardown()
self.folding_content = None
VerticalLayout.teardown(self) | Python |
# Copyright (c) 2009 Conrad "Lynx" Wong
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of DarkCoda nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""kytten - a skinnable, easily constructed GUI toolkit for pyglet
Inspired by simplui (Tristam MacDonald) and many other GUI projects.
Thanks to Gary Herron and Steve Johnson for debugging assistance!
"""
# GUI public constants
from layout import VALIGN_TOP, VALIGN_CENTER, VALIGN_BOTTOM
from layout import HALIGN_LEFT, HALIGN_CENTER, HALIGN_RIGHT
from layout import ANCHOR_TOP_LEFT, ANCHOR_TOP, ANCHOR_TOP_RIGHT, \
ANCHOR_LEFT, ANCHOR_CENTER, ANCHOR_RIGHT, \
ANCHOR_BOTTOM_LEFT, ANCHOR_BOTTOM, ANCHOR_BOTTOM_RIGHT
# GUI public classes
from button import Button
from checkbox import Checkbox
from dialog import Dialog, PopupMessage, PopupConfirm
from document import Document
from file_dialogs import FileLoadDialog, FileSaveDialog, DirectorySelectDialog
from frame import Frame, TitleFrame, Wrapper, SectionHeader, FoldingSection
from layout import GridLayout, HorizontalLayout, VerticalLayout, FreeLayout
from menu import Menu, Dropdown
from scrollable import Scrollable
from slider import Slider
from text_input import Input
from theme import Theme
from widgets import Widget, Spacer, Label
| Python |
# kytten/document.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import pyglet
from widgets import Control
from scrollbar import VScrollbar
class Document(Control):
"""
Allows you to embed a document within the GUI, which includes a
vertical scrollbar as needed.
"""
def __init__(self, document, width=1000, height=5000,
is_fixed_size=False, always_show_scrollbar=False):
"""
Creates a new Document.
"""
Control.__init__(self, width, height)
self.max_height = height
self.content_width = width
if isinstance(document, basestring):
self.document = pyglet.text.document.UnformattedDocument(document)
else:
self.document = document
self.content = None
self.content_width = width
self.scrollbar = None
self.set_document_style = False
self.is_fixed_size = is_fixed_size
self.always_show_scrollbar = always_show_scrollbar
self.needs_layout = False
def _do_set_document_style(self, attr, value):
length = len(self.document.text)
runs = [(start, end, doc_value) for start, end, doc_value in
self.document.get_style_runs(attr).ranges(0, length)
if doc_value is not None]
if not runs:
terminator = len(self.document.text)
else:
terminator = runs[0][0]
self.document.set_style(0, terminator, {attr: value})
def _get_controls(self):
controls = []
if self.scrollbar:
controls += self.scrollbar._get_controls()
controls += Control._get_controls(self)
return controls
def delete(self):
if self.content is not None:
self.content.delete()
self.content = None
if self.scrollbar is not None:
self.scrollbar.delete()
self.scrollbar = None
def do_set_document_style(self, dialog):
self.set_document_style = True
# Check the style runs to make sure we don't stamp on anything
# set by the user
self._do_set_document_style('color', dialog.theme['text_color'])
self._do_set_document_style('font_name', dialog.theme['font'])
self._do_set_document_style('font_size', dialog.theme['font_size'])
def get_text(self):
return self.document.text
def layout(self, x, y):
self.x, self.y = x, y
self.content.begin_update()
self.content.x = x
self.content.y = y
self.content.end_update()
if self.scrollbar is not None:
self.scrollbar.layout(x + self.content_width, y)
def on_update(self, dt):
"""
On updates, we update the scrollbar and then set our view offset
if it has changed.
@param dt Time passed since last update event (in seconds)
"""
if self.scrollbar is not None:
self.scrollbar.dispatch_event('on_update', dt)
pos = self.scrollbar.get(self.max_height,
self.content.content_height)
if pos != -self.content.view_y:
self.content.view_y = -pos
if self.needs_layout:
self.needs_layout = False
self.saved_dialog.set_needs_layout()
def size(self, dialog):
if dialog is None:
return
Control.size(self, dialog)
if not self.set_document_style:
self.do_set_document_style(dialog)
if self.content is None:
self.content = pyglet.text.layout.IncrementalTextLayout(
self.document,
self.content_width,
self.max_height,
multiline=True, batch=dialog.batch, group=dialog.fg_group)
if self.is_fixed_size or (self.max_height and
self.content.content_height > self.max_height):
self.height = self.max_height
else:
self.height = self.content.content_height
self.content.height = self.height
if self.always_show_scrollbar or \
(self.max_height and self.content.content_height > self.max_height):
if self.scrollbar is None:
self.scrollbar = VScrollbar(self.max_height)
self.scrollbar.size(dialog)
self.scrollbar.set(self.max_height, self.content.content_height)
if self.scrollbar is not None:
self.width = self.content_width + self.scrollbar.width
else:
self.width = self.content_width
def set_text(self, text):
self.document.text = text
self.needs_layout = True | Python |
import os
import pyglet
import kytten
from kytten import *
from kytten.widgets import Control, Widget
from kytten.layout import *
from kytten.dialog import Dialog
from kytten.frame import *
from kytten.button import *
from kytten.menu import *
class PaletteOption(Control):
"""
PaletteOption is a choice within a palette. It is similar to
MenuOption but contains an image/id instead of label/text. When
selected, it becomes highlighted to indicate it has been chosen.
"""
def __init__(self, id, image, scale_size=None, anchor=ANCHOR_CENTER,
palette=None, disabled=False, padding=0):
Control.__init__(self, disabled=disabled)
self.id = id
self.image = image
self.scale_size = scale_size
self.anchor = anchor
self.palette = palette
self.sprite = None
self.background = None
self.highlight = None
self.is_selected = False
self.padding = padding
def delete(self):
if self.sprite is not None:
self.sprite.delete()
self.sprite = None
if self.background is not None:
self.background.delete()
self.background = None
if self.highlight is not None:
self.highlight.delete()
self.highlight = None
#~ def expand(self, width, height):
#~ self.width = width
#~ self.height = height
#~ def is_expandable(self):
#~ return False
def layout(self, x, y):
self.x, self.y = x, y
if self.background is not None:
self.background.update(x, y, self.width, self.height)
if self.highlight is not None:
self.highlight.update(x, y, self.width, self.height)
#height = 32 #self.tile_height
w, h = self.sprite.width, self.sprite.height
x, y = GetRelativePoint(self, self.anchor,
Widget(w, h),
self.anchor, (0, 0))
self.sprite.x = x #+ self.padding / 2
self.sprite.y = y #+ self.padding / 2
#~ def on_gain_highlight(self):
#~ Control.on_gain_highlight(self)
#~ def on_lose_highlight(self):
#~ Control.on_lose_highlight(self)
def on_mouse_release(self, x, y, button, modifiers):
self.palette.select(self.id)#(self.text)
def select(self):
if self.is_disabled():
return # disabled options can't be selected
self.is_selected = True
self.size(self.saved_dialog) # to set up the highlight
if self.highlight is not None:
self.highlight.update(self.x, self.y,
self.width, self.height)
if self.saved_dialog is not None:
self.saved_dialog.set_needs_layout()
def size(self, dialog):
if dialog is None:
return
Control.size(self, dialog)
if self.is_selected:
path = ['menuoption', 'selection']
else:
path = ['menuoption']
if self.sprite is None:
if self.is_disabled():
opacity = 50
color = dialog.theme[path]['disabled_color']
else:
opacity = 255
color = dialog.theme[path]['text_color']
self.sprite = pyglet.sprite.Sprite(
self.image, batch=dialog.batch, group=dialog.fg_group)#, y=y, x=x, batch=self.tiles_batch)
self.sprite.opacity = opacity
if self.scale_size is not None:
self.sprite.scale = self.scale_size / float(self.sprite.width)
self.width = self.sprite.width + self.padding * 2
self.height = self.sprite.height + self.padding * 2
#~ if self.background is None:
#~ if self.is_selected:
#~ self.background = \
#~ dialog.theme[path]['highlight']['image'].generate(
#~ dialog.theme[path]['gui_color'],
#~ dialog.batch,
#~ dialog.bg_group)
if self.highlight is None:
if self.is_selected:
self.highlight = \
dialog.theme[path]['palette']['image'].generate(
dialog.theme[path]['input']['gui_color'],
dialog.batch,
dialog.highlight_group)
def unselect(self):
self.is_selected = False
if self.highlight is not None:
self.highlight.delete()
self.highlight = None
if self.background is not None:
self.background.delete()
self.background = None
if self.saved_dialog is not None:
self.saved_dialog.set_needs_layout()
def teardown(self):
self.palette = None
self.image = None
Control.teardown(self)
class TilePaletteOption(PaletteOption):
def __init__(self, id, image, scale_size=None, anchor=ANCHOR_CENTER,
palette=None, disabled=False, on_edit=None):
self.on_edit = on_edit
PaletteOption.__init__(self, id=id, image=image,
scale_size=scale_size, anchor=anchor,
palette=palette, disabled=disabled)
def on_mouse_release(self, x, y, button, modifiers):
if modifiers & pyglet.window.key.MOD_ACCEL:
if self.palette is not None:
self.on_edit(self.id)
PaletteOption.on_mouse_release(self, x, y, button, modifiers)
return True
class Palette(GridLayout):
"""
Palette is a GridLayout of PaletteOptions. Clicking a PaletteOption
selects it and causes Palette to send an on_click event.
"""
def __init__(self, options=[[]], padding=2, on_select=None ):
#~ menu_options = self._make_options(options)
GridLayout.__init__(self, options, padding=padding)
self.on_select = on_select
self.selected = None
self.options = {}
for row in options:
for option in row:
self.options[option.id] = option
if option is not None:
option.palette = self
if options[0][0] is not None:
self.select(options[0][0].id)
#self.on_select(self.get(0, 0).id)
#print self.selected
#~ def _make_options(self, options):
#~ menu_options = []
#~ for option in options:
#~ if option.startswith('-'):
#~ disabled = True
#~ option = option[1:]
#~ else:
#~ disabled = False
#~ menu_options.append(MenuOption(option,
#~ anchor=(VALIGN_CENTER, self.align),
#~ menu=self,
#~ disabled=disabled))
#~ return menu_options
def get_value(self):
return self.selected
def is_input(self):
return True
def select(self, id):
if self.selected is not None:
self.selected.unselect()
self.selected = self.options[id]
self.selected.select()
if self.on_select is not None:
self.on_select(id)
#print self.selected
def set_options(self, options):
self.delete()
self.selected = None
#menu_options = self._make_options(options)
#self.options = dict(zip(options, menu_options))
#~ i = 0
#~ for row in option:
#~ j = 0
#~ for cell in row:
#~ self.set(cell)
#~ j++
#~ i++
#~ self.set(menu_options)
self.saved_dialog.set_needs_layout()
def teardown(self):
self.on_select = None
GridLayout.teardown(self)
class HorizontalMenuOption(MenuOption):
def __init__(self, text="", anchor=ANCHOR_CENTER, menu=None,
disabled=False):
MenuOption.__init__(self, text=text, anchor=anchor, menu=menu,
disabled=disabled)
def on_gain_highlight(self):
Control.on_gain_highlight(self)
self.size(self.saved_dialog) # to set up the highlight
if self.highlight is not None:
self.highlight.update(self.x-self.menu.padding/2,
self.y,
self.width+self.menu.padding,
self.height)
def layout(self, x, y):
self.x, self.y = x, y
if self.background is not None:
self.background.update(x-self.menu.padding/2, y,
self.width+self.menu.padding, self.height)
if self.highlight is not None:
self.highlight.update(x-self.menu.padding/2, y,
self.width+self.menu.padding, self.height)
font = self.label.document.get_font()
height = font.ascent - font.descent
x, y = GetRelativePoint(self, self.anchor,
Widget(self.label.content_width, height),
self.anchor, (0, 0))
self.label.x = x
self.label.y = y - font.descent
def is_expandable(self):
return False
def select(self):
if self.is_disabled():
return # disabled options can't be selected
self.is_selected = True
if self.label is not None:
self.label.delete()
self.label = None
if self.saved_dialog is not None:
self.saved_dialog.set_needs_layout()
class HorizontalMenu(HorizontalLayout, Menu):
def __init__(self, options=[], align=VALIGN_CENTER, padding=8,
on_select=None):
Menu.__init__(self, options, padding=padding, on_select=on_select)
HorizontalLayout.__init__(self, self.content,
align=align, padding=padding)
def _make_options(self, options):
menu_options = []
for option in options:
if option.startswith('-'):
disabled = True
option = option[1:]
else:
disabled = False
menu_options.append(HorizontalMenuOption(option,
anchor=(VALIGN_CENTER, self.align),
menu=self,
disabled=disabled))
return menu_options
def layout(self, x, y):
"""
Lays out the child Widgets, in order from left to right.
@param x X coordinate of the lower left corner
@param y Y coordinate of the lower left corner
"""
Widget.layout(self, x, y)
# Expand any expandable content to our height
for item in self.content:
if item.is_expandable() and item.height < self.height:
item.expand(item.width, self.height)
left = x+self.padding/2
if self.align == VALIGN_TOP:
for item in self.content:
item.layout(left, y + self.height - item.height)
left += item.width + self.padding
elif self.align == VALIGN_CENTER:
for item in self.content:
item.layout(left, y + self.height/2 - item.height/2)
left += item.width + self.padding
else: # VALIGN_BOTTOM
for item in self.content:
item.layout(left, y)
left += item.width + self.padding
def size(self, dialog):
"""
Calculates size of the layout, based on its children.
@param dialog The Dialog which contains the layout
"""
if dialog is None:
return
Widget.size(self, dialog)
height = 0
if len(self.content) < 2:
width = 0
else:
width = -self.padding
for item in self.content:
item.size(dialog)
height = max(height, item.height)
width += item.width + self.padding
self.width, self.height = width+self.padding, height
self.expandable = [x for x in self.content if x.is_expandable()]
class NoSelectMenu(Menu):
"""
A menu that does not stay selected.
"""
def __init__(self, options=[], align=HALIGN_CENTER, padding=4,
on_select=None):
Menu.__init__(self, options=options, align=align,
padding=padding, on_select=on_select)
def select(self, text):
if not text in self.options:
return
if self.selected is not None:
self.options[self.selected].unselect()
self.selected = text
menu_option = self.options[text]
#menu_option.select()
if self.on_select is not None:
self.on_select(text)
class PropertyDialog(Dialog):
"""
An ok/cancel-style dialog for editing properties. Options must be a
dictionary of name/values. Escape defaults to cancel.
@ has_remove allows for deleting options and returns
@ _REMOVE_PRE+option id = True for get_values()
"""
_id_count = 0
REMOVE_PRE = '_X!'
TYPE_PRE = '_T!'
ADD_NAME_PRE = '_N!'
ADD_VALUE_PRE = '_V!'
INPUT_W = 12
def __init__(self, title="", properties={}, ok="Ok", cancel="Cancel",
window=None, batch=None, group=None, theme=None,
on_ok=None, on_cancel=None, has_remove=False,
remove="x", has_add=False, add="+", on_add=None):
def on_ok_click(dialog=None):
if on_ok is not None:
on_ok(self)
#self.teardown()
def on_cancel_click(dialog=None):
if on_cancel is not None:
on_cancel(self)
#self.teardown()
self.remove = remove
self._has_remove = has_remove
self._has_add = has_add
property_table = self._make_properties(properties)
grid = GridLayout(property_table, padding=8)
def on_type_select(id, choice):
item = Checkbox() if choice is 'bool' else Input(length=self.INPUT_W)
for i, row in enumerate(grid.content):
for cell in row:
if isinstance(cell, Dropdown):
if cell.id == id:
item_id = grid.get(1,i).id
item.id = item_id
grid.set(row=i, column=1, item=item)
break
def on_add_click(dialog=None):
if on_add is not None:
on_add(self)
else:
pd = PropertyDialog
pd._id_count += 1
grid.add_row([
Input(id=pd.ADD_NAME_PRE+str(pd._id_count),
length=self.INPUT_W),
Input(id=pd.ADD_VALUE_PRE+str(pd._id_count),
length=self.INPUT_W),
Dropdown(['unicode', 'bool', 'int', 'float'],
id=pd.TYPE_PRE+str(pd._id_count),
on_select=on_type_select)
])
if self._has_add:
add_content = (ANCHOR_TOP_LEFT, 0, 0, Button(add, on_click=on_add_click))
Dialog.__init__(self, content=Frame(Scrollable(
VerticalLayout([
SectionHeader(title, align=HALIGN_LEFT),
grid,
FreeLayout(content=[add_content]),
Spacer(height=30),
HorizontalLayout([
Button(ok, on_click=on_ok_click),
Button(cancel, on_click=on_cancel_click)])
]),height=window.height)),
window=window, batch=batch, group=group,
theme=theme, movable=True,
on_enter=on_ok_click, on_escape=on_cancel_click)
else:
Dialog.__init__(self, content=Frame(Scrollable(
VerticalLayout([
SectionHeader(title, align=HALIGN_LEFT),
grid,
Spacer(height=30),
HorizontalLayout([
Button(ok, on_click=on_ok_click),
Button(cancel, on_click=on_cancel_click)])
]),height=window.height)),
window=window, batch=batch, group=group,
theme=theme, movable=True,
on_enter=on_ok_click, on_escape=on_cancel_click)
def _make_properties(self, properties):
property_table = [[]]
for name, value in properties:
if isinstance(value, bool):
property = Checkbox(is_checked=value, id=name)
else:
property = Input(name, unicode(value), length=self.INPUT_W)
if self._has_remove:
property_table.append([Label(name), property,
Checkbox(self.remove,
id=PropertyDialog.REMOVE_PRE+name)])
else:
property_table.append([Label(name), property])
return property_table
| Python |
import pyglet
import cocos
from cocos.director import director
import kytten
class DialogNode(cocos.batch.BatchableNode):
def __init__(self, dialog=None):
super(DialogNode, self).__init__()
self.dialog = dialog
def set_batch(self, batch, group=None, z=0):
super(DialogNode, self).set_batch(batch, group)
if self.dialog is not None:
self.dialog.batch = self.batch
self.dialog.group = self.group
def delete(self, dialog=None):
self.dialog.teardown()
super(DialogNode, self).on_exit()
self.parent.remove(self)
def draw(self):
pass
class DialogLayer(cocos.layer.Layer):
is_event_handler = True
def __init__(self, dialog=None):
super(DialogLayer, self).__init__()
self.batchnode = cocos.batch.BatchNode()
#self.batchnode.position = 50,100
self.add(self.batchnode)
#self.batch = pyglet.graphics.Batch()
#self.group = pyglet.graphics.OrderedGroup(0)
director.window.register_event_type('on_update')
def update(dt):
director.window.dispatch_event('on_update', dt)
self.schedule(update)
def add_dialog(self, dialog_node):
if dialog_node is not None:
self.batchnode.add(dialog_node)
def on_key_press(self, symbol, modifiers):
for c in self.batchnode.get_children():
if c.dialog.focus and hasattr(c.dialog.focus,
'on_key_press'):
return True
def on_key_release(self, symbol, modifiers):
for c in self.batchnode.get_children():
if c.dialog.on_key_release(symbol, modifiers):
return True
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
for c in self.batchnode.get_children():
if c.dialog.on_mouse_drag(x, y, dx, dy, buttons, modifiers) \
or c.dialog.focus != None:
return True
def on_mouse_motion(self, x, y, dx, dy):
for c in self.batchnode.get_children():
c.dialog.on_mouse_motion(x, y, dx, dy)
if c.dialog.hover is not None:
return True
#~ else:
#~ c.dialog.set_focus(None)
def on_mouse_press(self, x, y, button, modifiers):
was_handled = False
for c in self.batchnode.get_children():
if c.dialog.on_mouse_press(x, y, button, modifiers):
was_handled = True
else:
c.dialog.set_wheel_hint(None)
c.dialog.set_wheel_target(None)
return was_handled
def on_mouse_release(self, x, y, button, modifiers):
was_handled = False
for c in self.batchnode.get_children():
if c.dialog.on_mouse_release(x, y, button, modifiers):
was_handled = True
return was_handled
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
for c in self.batchnode.get_children():
if c.dialog.on_mouse_scroll(x, y, scroll_x, scroll_y):
return True
def on_text(self, text):
for c in self.batchnode.get_children():
if c.dialog.focus and hasattr(c.dialog.focus, 'on_text'):
return True
def on_text_motion(self, motion):
for c in self.batchnode.get_children():
if c.dialog.focus and hasattr(c.dialog.focus,
'on_text_motion'):
return True
def on_text_motion_select(self, motion):
for c in self.batchnode.get_children():
if c.dialog.focus and hasattr(c.dialog.focus,
'on_text_motion_select'):
return True
| Python |
'''
Copyright (c) 2009, Devon Scott-Tunkin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Thanks to Richard Jones for his original editor and tile library
and Conrad Wong for the "kytten" gui library
Cocograph tile map editor for cocos2d
'''
import os
import glob
import weakref
from xml.etree import ElementTree
import pyglet
# Disable error checking for increased performance
pyglet.options['debug_gl'] = False
from pyglet.gl import *
import cocos
from cocos import tiles, actions
import kytten
from tile_widgets import *
from dialog_node import *
#? moved theme into the same dir as this, file so adjust the loading
##the_theme = kytten.Theme(os.path.join(os.getcwd(), 'theme'), override={
## "gui_color": [255, 235, 128, 255],
## "font_size": 12,
##}) # original in cocograph
theme_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)),'theme')
the_theme = kytten.Theme(theme_dir, override={
"gui_color": [255, 235, 128, 255],
"font_size": 12,
})
the_image_extensions = ['.png', '.jpg', '.bmp', '.gif', '.tga']
def texture_set_mag_filter_nearest(texture):
glBindTexture(texture.target, texture.id)
glTexParameteri(texture.target, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glBindTexture(texture.target, 0)
def on_prop_container_edit(prop_container, parent_dnode, filename=None):
if prop_container is None:
return
options = prop_container.properties.iteritems()
dnode = DialogNode()
def on_submit(dialog):
pd = PropertyDialog
for k, v in dialog.get_values().iteritems():
# Check prefix is not removal value
if not k.startswith(pd.REMOVE_PRE) \
and not k.startswith(pd.TYPE_PRE) \
and not k.startswith(pd.ADD_NAME_PRE):
# If matching removal prefix + key is true, remove
if dialog.get_value(pd.REMOVE_PRE+k):
del prop_container.properties[k]
# If new property find matching name and type then add
elif k.startswith(pd.ADD_VALUE_PRE):
id_num = k.lstrip(pd.ADD_VALUE_PRE)
v_name = dialog.get_value(pd.ADD_NAME_PRE+id_num)
v_type = dialog.get_value(pd.TYPE_PRE+id_num)
if v_type is not 'bool':
v_type = tiles._xml_to_python[v_type]
else:
v_type = bool
prop_container.properties[v_name] = v_type(v)
# Otherwise change to new value and cast to old type
else:
prop_container.properties[k] = \
type(prop_container.properties[k])(v)
if isinstance(prop_container, tiles.Tile):
for ns, res in parent_dnode.level_to_edit.requires:
if prop_container in res.contents.itervalues():
resource = res
dirname = os.path.dirname(parent_dnode.level_to_edit.filename)
xmlname = os.path.join(dirname, resource.filename)
in_tree = ElementTree.parse(xmlname)
root = ElementTree.Element('resource')
root.text = '\n'
root.tail = '\n'
for namespace, res in resource.requires:
r_element = ElementTree.SubElement(root, 'requires',
file=res.filename)
r_element.tail = '\n'
if namespace:
r_element.set('namespace', namespace)
for img_element in in_tree.findall('image'):
root.append(img_element)
for atlas_element in in_tree.findall('imageatlas'):
root.append(atlas_element)
tset_element = _generic_as_xml(
parent_dnode.active_tileset, root, 'tileset')
for n, k in enumerate(parent_dnode.active_tileset):
t = parent_dnode.active_tileset[k]
t_element = _generic_as_xml(t, tset_element, 'tile')
if t.offset:
t_element.set('offset', t.offset)
for k, v in resource.contents.iteritems():
if t.image is v:
img_element = ElementTree.SubElement(
t_element, 'image', ref=k)
img_element.tail = '\n'
out_tree = ElementTree.ElementTree(root)
out_tree.write(xmlname)
dnode.delete()
try:
id = prop_container.id
except AttributeError:
id = ''
dnode.dialog = PropertyDialog(id, properties=options,
window=parent_dnode.dialog.window,
theme=parent_dnode.dialog.theme,
on_ok=on_submit,
on_cancel=dnode.delete,
has_remove=True, has_add=True)
parent_dnode.parent.add(dnode)
def _generic_as_xml(resource, parent, tag):
element = ElementTree.SubElement(parent, tag)
element.text = '\n'
element.tail = '\n'
if resource.id:
element.set('id', resource.id)
for k in resource.properties:
v = resource.properties[k]
vs = tiles._python_to_xml[type(v)](v)
p = ElementTree.SubElement(element, 'property', name=k, value=vs,
type=tiles._xml_type[type(v)])
p.tail = '\n'
return element
class TilesetDialog(DialogNode):
_id_count = 0
def __init__(self, window=None, level_to_edit=None, tile_size=32):
self.level_to_edit = level_to_edit
self.tilesets = {}
self.tile_size = tile_size
self.selected = None
self.palettes = {}
self.vlayout = None
self._load_tilesets(level_to_edit)
def on_menu_select(choice):
if choice == 'From Dir':
self._create_from_directory_dialog()
elif choice == 'From Image':
self._create_from_image_dialog()
elif choice == 'Open':
dnode = DialogNode()
def on_open_click(filename):
r = tiles.load(filename)
# XXX Maybe more error checking?
self._load_tilesets(r)
self._make_resource_relative(r)
dnode.dialog.on_escape(dnode.dialog)
dnode.dialog = kytten.FileLoadDialog(
extensions=['.xml'], window=self.dialog.window,
theme=self.dialog.theme,
on_select=on_open_click,
on_escape=dnode.delete)
self.parent.add(dnode)
def on_palette_select(id):
if self.vlayout.saved_dialog is not None:
self.active_tileset = self.tilesets[id]
self.active_palette = self.palettes[id]
self.vlayout.set([self.palette_menu, self.active_palette])
#~ self.active_palette.select(
#~ self.active_palette.options.iterkeys().next())
# Create tabs of tilesets
self.palette_menu = HorizontalMenu([
k for k, v in self.palettes.iteritems()],
padding=16,
on_select=on_palette_select)
# Combine tabs and palette
self.vlayout = kytten.VerticalLayout(
[self.palette_menu, self.active_palette],
align=kytten.HALIGN_LEFT)
# Create tileset file menu
self.file_menu = kytten.VerticalLayout([
kytten.SectionHeader("Tileset"),
NoSelectMenu(['From Dir', 'From Image', 'Open'],
on_select=on_menu_select)])
# Create final combined tileset dialog
self.hlayout = kytten.HorizontalLayout(
[self.file_menu, self.vlayout])
self.scrollable = kytten.Scrollable(self.hlayout,
width=window.width-30)
super(TilesetDialog, self).__init__(
kytten.Dialog(
kytten.Frame(self.scrollable),
window=window,
anchor=kytten.ANCHOR_BOTTOM,
theme=the_theme))
# Make first palette active
try:
self.palette_menu.select(self.palettes.iterkeys().next())
except:
pass
def select_tile(self, id):
for tset_id, tset in self.tilesets.iteritems():
if id in tset:
self.palette_menu.select(tset_id)
self.active_palette.select(id)
def _load_tilesets(self, resource):
select_id = ''
for id, ts in resource.findall(tiles.TileSet):
if id is None:
self._id_count += 1
id = 'Untitled' + str(self._id_count)
self.tilesets[id] = ts
select_id = id
try:
self.active_tileset = resource.findall(
tiles.TileSet).next()[1]
except:
self.active_tileset = None
def on_tile_select(id):
try:
self.selected = self.active_tileset[id]
except KeyError:
pass
for id, tset in self.tilesets.iteritems():
tile_options = [[]]
tile_options.append([])
for i, k in enumerate(sorted(tset)): # Sort to keep order
texture_set_mag_filter_nearest(tset[k].image.get_texture())
option = TilePaletteOption(
id=k,
image=tset[k].image,
scale_size=self.tile_size,
on_edit=self._on_tile_edit)
tile_options[i%2].append(option)
self.palettes[id] = Palette(tile_options,
on_select=on_tile_select)
try:
self.active_palette = self.palettes.itervalues().next()
except:
self.active_palette = None
if self.vlayout is not None:
self.palette_menu.set_options(
[k for k, v in self.palettes.iteritems()])
self.palette_menu.select(select_id)
self.vlayout.set([self.palette_menu, self.active_palette])
def _on_tile_edit(self, id):
tile = self.active_tileset[id]
on_prop_container_edit(tile, self)
def _make_resource_relative(self, resource):
# Tilesets filename should be relative to maps
level_dir = os.path.split(
self.level_to_edit.filename)[0] + os.sep
# Remove map path from tileset filename
if level_dir is not '/':
resource.filename = resource.filename.replace(level_dir, '')
resource.filename = resource.filename.replace('\\', '/')
self.level_to_edit.requires.append(('', resource))
def _save_directory_xml(self, filepath, filenames):
root = ElementTree.Element('resource')
root.tail = '\n'
for filename in filenames:
img_element = ElementTree.SubElement(
root,
'image',
id='i-' + os.path.splitext(filename)[0],
file=filename)
img_element.tail = '\n'
xmlname = os.path.splitext(os.path.basename(filepath))[0]
tset_element = ElementTree.SubElement(
root,
'tileset',
id=xmlname)
tset_element.tail = '\n'
for filename in filenames:
t_element = ElementTree.SubElement(
tset_element,
'tile',
id=os.path.splitext(filename)[0])
t_element.tail = '\n'
img_element = ElementTree.SubElement(
t_element,
'image',
ref='i-'+os.path.splitext(filename)[0])
tree = ElementTree.ElementTree(root)
tree.write(filepath)
r = tiles.load(filepath)
self._load_tilesets(r)
self._make_resource_relative(r)
def _save_image_xml(self, xmlpath, imagepath, tw, th, padding):
img = pyglet.image.load(imagepath)
root = ElementTree.Element('resource')
root.text = '\n'
root.tail = '\n'
size = tw + 'x' + th
tw = int(tw)
th = int(th)
padding = int(padding)
double_padding = padding * 2
xmlname = os.path.splitext(os.path.basename(xmlpath))[0]
# Remove xml path from image path to get relative path
xmldir = os.path.split(xmlpath)[0] + os.sep
imagepath = imagepath.replace(xmldir, '')
atlas_element = ElementTree.SubElement(root, 'imageatlas',
size=size, file=imagepath)
atlas_element.text = '\n'
atlas_element.tail = '\n'
for x in range(padding, img.width, tw + double_padding):
for y in range(padding, img.height, th + double_padding):
img_element = ElementTree.SubElement(
atlas_element,
'image',
id='i-%s-%d-%d' % (xmlname, x, y),
offset='%d,%d' % (x, y))
img_element.tail = '\n'
tset_element = ElementTree.SubElement(root, 'tileset', id=xmlname)
tset_element.text = '\n'
tset_element.tail = '\n'
for x in range(padding, img.width, tw + double_padding):
for y in range(padding, img.height, th + double_padding):
t_element = ElementTree.SubElement(
tset_element,
'tile',
id='%s-%d-%d' % (xmlname, x, y))
t_element.tail = '\n'
ElementTree.SubElement(
t_element,
'image',
ref='i-%s-%d-%d' % (xmlname, x, y))
tree = ElementTree.ElementTree(root)
tree.write(xmlpath)
r = tiles.load(xmlpath)
self._load_tilesets(r)
self._make_resource_relative(r)
def _create_from_directory_dialog(self):
dnode = DialogNode()
def on_select_click(dirpath):
filepaths = glob.glob(os.path.join(dirpath, '*'))
filenames = []
for filepath in filepaths:
if os.path.isfile(filepath):
ext = os.path.splitext(filepath)[1]
if ext in the_image_extensions:
filenames.append(os.path.basename(filepath))
if len(filenames) is not 0:
save_dnode = DialogNode()
def on_save(filepath):
self._save_directory_xml(filepath, filenames)
save_dnode.dialog.on_escape(save_dnode.dialog)
save_dnode.dialog = kytten.FileSaveDialog(
path=dirpath,
extensions=['.xml'],
title='Save Tileset As',
window=self.dialog.window,
theme=self.dialog.theme,
on_select=on_save,
on_escape=save_dnode.delete)
self.parent.add(save_dnode)
dnode.dialog.on_escape(dnode.dialog)
dnode.dialog = kytten.DirectorySelectDialog(
title='Select Directory of Images',
window=self.dialog.window,
theme=self.dialog.theme,
on_select=on_select_click,
on_escape=dnode.delete)
self.parent.add(dnode)
def _create_from_image_dialog(self):
dnode = DialogNode()
def on_open_click(imagepath):
prop_dnode = DialogNode()
options = []
tw = 'Tile Width (px)'
th = 'Tile Height (px)'
pad = 'Padding (px)'
map = self.level_to_edit.find(tiles.MapLayer).next()[1]
options.append((tw, map.tw))
options.append((th, map.th))
options.append((pad,'0'))
def on_submit(dialog):
values = dialog.get_values()
def on_save(filepath):
self._save_image_xml(filepath, imagepath,
values[tw], values[th],
values[pad])
save_dnode.dialog.on_escape(save_dnode.dialog)
save_dnode.dialog = kytten.FileSaveDialog(
extensions=['.xml'],
title='Save Tileset As',
window=self.dialog.window,
theme=self.dialog.theme,
on_select=on_save,
on_escape=save_dnode.delete)
self.parent.add(save_dnode)
prop_dnode.dialog.on_escape(prop_dnode.dialog)
prop_dnode.dialog = PropertyDialog(
'New Tileset',
properties=options,
window=self.dialog.window,
theme=self.dialog.theme,
on_ok=on_submit,
on_cancel=prop_dnode.delete)
self.parent.add(prop_dnode)
save_dnode = DialogNode()
dnode.dialog.on_escape(dnode.dialog)
dnode.dialog = kytten.FileLoadDialog(
extensions=the_image_extensions,
window=self.dialog.window,
theme=self.dialog.theme,
on_select=on_open_click,
on_escape=dnode.delete)
self.parent.add(dnode)
class ToolMenuDialog(DialogNode):
def __init__(self, window, on_new=None, on_open=None, on_save=None,
map_layers=[], level_to_edit=None):
self.on_new = on_new
self.on_open = on_open
self.on_save = on_save
self.map_layers = map_layers
self.level_to_edit = level_to_edit
tool_layout = self._make_tool_layout()
layer_layout = self._make_layer_layout()
map_menu_layout = self._make_map_menu_layout()
super(ToolMenuDialog, self).__init__(kytten.Dialog(
kytten.Frame(
kytten.Scrollable(
kytten.VerticalLayout([
tool_layout,
kytten.FoldingSection('Layer', layer_layout),
kytten.FoldingSection('Map', map_menu_layout),
], align=kytten.HALIGN_CENTER))
),
window=window,
anchor=kytten.ANCHOR_TOP_LEFT,
theme=the_theme))
# Select last layer
if len(self.map_layers):
self.layer_menu.select(self.map_layers[-1].id)
#self.layer_menu = layer_m
def _add_opacity(self, layer):
# Add opacity functionality to layer instance
layer.opacity = 255
# Probably a way to do this with decorators?
def enhance(lyr):
set_dirty = lyr.set_dirty
def set_dirty_and_opacity():
set_dirty()
for s in lyr._sprites.itervalues():
s.opacity = lyr.opacity
return set_dirty_and_opacity
layer.set_dirty = enhance(layer)
def _make_tool_layout(self):
# Load images into a list
images = []
images.append(('move',pyglet.image.load(
os.path.join(theme_dir, 'artlibre', 'transform-move.png'))))
images.append(('eraser',pyglet.image.load(
os.path.join(theme_dir, 'artlibre', 'draw-eraser.png'))))
images.append(('picker',pyglet.image.load(
os.path.join(theme_dir, 'artlibre', 'color-picker.png'))))
images.append(('zoom',pyglet.image.load(
os.path.join(theme_dir, 'artlibre', 'page-magnifier.png'))))
images.append(('pencil',pyglet.image.load(
os.path.join(theme_dir, 'artlibre', 'draw-freehand.png'))))
images.append(('fill',pyglet.image.load(
os.path.join(theme_dir, 'artlibre', 'color-fill.png'))))
# Create options from images to pass to Palette
palette_options = [[]]
palette_options.append([])
palette_options.append([])
for i, pair in enumerate(images):
option = PaletteOption(id=pair[0], image=pair[1], padding=4)
# Build column down, 3 rows
palette_options[i%3].append(option)
def on_tool_select(id):
self.active_tool = id
layout = Palette(palette_options, on_select=on_tool_select)
return layout
def _make_layer_layout(self):
for layer in self.map_layers:
self._add_opacity(layer)
# Reverse order for menu so layer names are top to bottom
layer_options = [layer.id for layer in reversed(self.map_layers)]
if len(self.map_layers):
def on_opacity_set(value):
m = self.map_layers.selected
m.opacity = int(value)
m.set_dirty()
#~ for s in m._sprites.itervalues():
#~ s.opacity = value
#self.map_layers.selected.set_dirty()
else:
on_opacity_set = None
opacity_slider = kytten.Slider(value=255, max_value=255,steps=8,
width=10, on_set=on_opacity_set)
def on_layer_select(id):
for i, layer in enumerate(self.map_layers):
if layer.id is id:
self.map_layers.select(i)
opacity_slider.set_pos(
self.map_layers.selected.opacity / 255.0)
self.layer_menu = kytten.Menu(layer_options, on_select=on_layer_select)
if len(self.map_layers):
def on_add_layer():
dnode = DialogNode()
ID = 'Layer ID'
TW = 'Tile Width (px)'
TH = 'Tile Height (px)'
OZ = 'Z Origin'
selected = self.map_layers.selected
tile_width = selected.tw
tile_height = selected.th
origin_z = selected.origin_z + 1
#? flipped, the new was getting transposed dimensions
col_count = len(selected.cells[0])
row_count = len(selected.cells)
options = [(ID, ''), (TW, tile_width), (TH, tile_height),
(OZ, origin_z)]
cells = [[tiles.RectCell(i, j, tile_width, tile_height, {}, None)
for j in range(col_count)] for i in range(row_count)]
def on_submit(dialog):
values = dialog.get_values()
layer = tiles.RectMapLayer(values[ID], int(values[TW]),
int(values[TH]), cells,
(0, 0, int(values[OZ])), {})
self._add_opacity(layer)
self.map_layers.append(layer)
self.map_layers.sort(lambda x, y: x.origin_z - y.origin_z)
selected.parent.add(layer, z=layer.origin_z)
self.level_to_edit.contents[layer.id] = layer
self.layer_menu.set_options(
[l.id for l in reversed(self.map_layers)])
self.layer_menu.select(layer.id)
dnode.dialog.on_escape(dnode.dialog)
dnode.dialog = PropertyDialog(
'New Layer',
properties=options,
window=self.dialog.window,
theme=self.dialog.theme,
on_ok=on_submit,
on_cancel=dnode.delete)
self.parent.add(dnode)
def on_remove_layer():
layers = self.map_layers
if len(layers) > 1:
layers.selected.parent.remove(layers.selected) # scrolling manager
layers.remove(layers.selected) # map layers / layer selector
del self.level_to_edit.contents[layers.selected.id] # resource
self.layer_menu.set_options([l.id for l in reversed(layers)])
self.layer_menu.select(layers[-1].id)
def on_layer_prop_edit(choice):
on_prop_container_edit(self.map_layers.selected, self)
else:
on_add_layer = None
on_remove_layer = None
on_layer_prop_edit = None
on_opacity_set = None
layout = kytten.VerticalLayout([
kytten.HorizontalLayout([
kytten.Label('op'),
opacity_slider]),
self.layer_menu,
kytten.HorizontalLayout([
kytten.Button('+', on_click=on_add_layer),
kytten.Button('x', on_click=on_remove_layer)]),
NoSelectMenu(
options=['Properties'],
on_select=on_layer_prop_edit),])
return layout
def _make_map_menu_layout(self):
def on_select(choice):
if choice == 'New':
self._create_new_dialog()
elif choice == 'Open':
self._create_open_dialog()
elif choice == 'Save':
if self.on_save is not None:
self.on_save()
elif choice == 'Quit':
director.pop()
layout = kytten.VerticalLayout([
NoSelectMenu(
options=['New', 'Open', 'Save', 'Quit'],
on_select=on_select)])
return layout
def _create_new_dialog(self):
dnode = DialogNode()
options = []
#mid = 'Map ID'
# Options for new map form
tw = 'Tile Width (px)'
th = 'Tile Height (px)'
mw = 'Map Width (tiles)'
mh = 'Map Height (tiles)'
#mo = 'Map Origin (x,y,z)'
#options.append((mid,""))
options.append((tw,""))
options.append((th,""))
options.append((mw,""))
options.append((mh,""))
#options.append((mo,"0,0,0"))
def on_submit(dialog):
root = ElementTree.Element('resource')
root.tail = '\n'
v = dialog.get_values()
save_dnode = DialogNode()
def on_save(filename):
xmlname = os.path.basename(filename)
m = ElementTree.SubElement(root, 'rectmap',
id=os.path.splitext(xmlname)[0],
tile_size='%dx%d'%(int(v[tw]), int(v[th])),
origin='%s,%s,%s'%(0, 0, 0))
m.tail = '\n'
for column in range(int(v[mw])):
col = ElementTree.SubElement(m, 'column')
col.tail = '\n'
for cell in range(int(v[mh])):
c = ElementTree.SubElement(col, 'cell')
c.tail = '\n'
tree = ElementTree.ElementTree(root)
tree.write(filename)
if self.on_open is not None:
self.on_open(filename)
save_dnode.dialog.on_escape(save_dnode.dialog)
save_dnode.dialog = kytten.FileSaveDialog(
extensions=['.xml'],
title='Save Map As',
window=self.dialog.window,
theme=self.dialog.theme,
on_select=on_save,
on_escape=save_dnode.delete)
self.parent.add(save_dnode)
dnode.dialog.on_escape(dnode.dialog)
dnode.dialog = PropertyDialog('New Map', properties=options,
window=self.dialog.window,
theme=self.dialog.theme,
on_ok=on_submit,
on_cancel=dnode.delete)
self.parent.add(dnode)
def _create_open_dialog(self):
dnode = DialogNode()
def on_open_click(filename):
if self.on_open is not None:
self.on_open(filename)
dnode.dialog.on_escape(dnode.dialog)
dnode.dialog = kytten.FileLoadDialog(
extensions=['.xml'], window=self.dialog.window,
theme=self.dialog.theme,
on_select=on_open_click,
on_escape=dnode.delete)
self.parent.add(dnode)
| Python |
'''
Copyright (c) 2009, Devon Scott-Tunkin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Thanks to Richard Jones for his original editor and tile library
and Conrad Wong for the "kytten" gui library
Cocograph tile map editor for cocos2d
'''
from cocos.director import director
from tile_dialogs import *
VERSION = 'Cocograph 0.2.0'
def _zoom_in(scale):
if scale > 4: return scale
else: return scale * 2.0
def _zoom_out(scale):
if scale < .01: return scale
else: return scale / 2.0
class TileEditorLayer(tiles.ScrollableLayer):
is_event_handler = True
def __init__(self, tiles, tools, level_to_edit=None, filename=None,
map_layers=None,):
super(TileEditorLayer, self).__init__()
self.level_to_edit = level_to_edit
self.filename = filename
self.highlight = None
self.tiles = tiles
self.tools = tools
self.map_layers = map_layers
w, h = director.get_window_size()
_space_down = False
def on_key_press(self, key, modifier):
# Don't exit on ESC
if key == pyglet.window.key.ESCAPE:
return True
#~ elif key == pyglet.window.key.S:
#~ self.level_to_edit.save_xml(self.filename)
if modifier & pyglet.window.key.MOD_ACCEL:
if key == pyglet.window.key.Q:
director.pop()
elif key == pyglet.window.key.MINUS:
self._desired_scale = _zoom_out(self._desired_scale)
self.parent.set_scale(self._desired_scale)
elif key == pyglet.window.key.EQUAL:
self._desired_scale = _zoom_in(self._desired_scale)
self.parent.set_scale(self._desired_scale)
elif key == pyglet.window.key.D:
m = self.map_layers.selected
m.set_debug(not m.debug)
if key == pyglet.window.key.SPACE:
self._space_down = True
win = director.window
cursor = win.get_system_mouse_cursor(pyglet.window.Window.CURSOR_SIZE)
win.set_mouse_cursor(cursor)
def on_key_release(self, key, modifier):
if key == pyglet.window.key.SPACE:
self._space_down = False
win = director.window
win.set_mouse_cursor()
return True
return True
_desired_scale = 1
def on_mouse_scroll(self, x, y, dx, dy):
if dy < 0:
self._desired_scale = _zoom_out(self._desired_scale)
#self.parent.set_scale(self._desired_scale)
elif dy > 0:
self._desired_scale = _zoom_in(self._desired_scale)
#self.parent.set_scale(self._desired_scale)
if dy:
self.parent.do(actions.ScaleTo(self._desired_scale, .1))
return True
def on_text_motion(self, motion):
fx, fy = self.parent.fx, self.parent.fy
if motion == pyglet.window.key.MOTION_UP:
self.parent.force_focus(fx, fy+64/self._desired_scale)
elif motion == pyglet.window.key.MOTION_DOWN:
self.parent.force_focus(fx, fy-64/self._desired_scale)
elif motion == pyglet.window.key.MOTION_LEFT:
self.parent.force_focus(fx-64/self._desired_scale, fy)
elif motion == pyglet.window.key.MOTION_RIGHT:
self.parent.force_focus(fx+64/self._desired_scale, fy)
else:
return False
return True
_dragging = False
def on_mouse_press(self, x, y, buttons, modifiers):
self._drag_start = (x, y)
self._dragging = False
if not self._space_down:
m = self.map_layers.selected
mx, my = self.parent.pixel_from_screen(x, y)
cell = m.get_at_pixel(mx, my)
if not cell:
# click not in map
return
self._current_cell = cell
cx, cy = sprite_key = cell.origin[:2]
# ctrl-click edit tile properties
if modifiers & pyglet.window.key.MOD_ACCEL:
on_prop_container_edit(cell, self.tiles)
elif self.tools.active_tool is 'zoom':
if buttons & pyglet.window.mouse.LEFT:
self._desired_scale = _zoom_in(self._desired_scale)
elif buttons & pyglet.window.mouse.RIGHT:
self._desired_scale = _zoom_out(self._desired_scale)
self.parent.set_scale(self._desired_scale)
elif self.tools.active_tool is 'pencil':
if buttons & pyglet.window.mouse.LEFT:
cell.tile = self.tiles.selected
# Set dirty is not dirty enough for performance
m._sprites[sprite_key] = pyglet.sprite.Sprite(
cell.tile.image, x=cx, y=cy, batch=m.batch)
m._sprites[sprite_key].opacity = m.opacity
#m.set_dirty()
# Picker
elif buttons & pyglet.window.mouse.RIGHT:
if cell.tile is not None:
self.tiles.select_tile(cell.tile.id)
elif self.tools.active_tool is 'eraser':
if cell.tile is not None:
cell.tile = None
del m._sprites[sprite_key] # Clear properties
elif self.tools.active_tool is 'picker':
if cell.tile is not None:
self.tiles.select_tile(cell.tile.id)
elif self.tools.active_tool is 'fill':
if self.tiles.selected is cell.tile:
return True
old_tile = cell.tile
cells_to_fill = []
cells_to_fill.append(cell)
while len(cells_to_fill):
c = cells_to_fill.pop()
c.tile = self.tiles.selected
next_c = m.get_neighbor(c, m.RIGHT)
if next_c and next_c.tile is old_tile:
cells_to_fill.append(next_c)
next_c = m.get_neighbor(c, m.LEFT)
if next_c and next_c.tile is old_tile:
cells_to_fill.append(next_c)
next_c = m.get_neighbor(c, m.UP)
if next_c and next_c.tile is old_tile:
cells_to_fill.append(next_c)
next_c = m.get_neighbor(c, m.DOWN)
if next_c and next_c.tile is old_tile:
cells_to_fill.append(next_c)
m.set_dirty()
return True
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
if not self._dragging and self._drag_start:
_x, _y = self._drag_start
if abs(x - _x) + abs(y - _y) < 6:
return False
self._dragging = True
if self._space_down or self.tools.active_tool is 'move':
self.parent.force_focus(
self.parent.fx-(dx/self._desired_scale),
self.parent.fy-(dy/self._desired_scale))
return True
if self.tools.active_tool is 'pencil' or 'eraser':
m = self.map_layers.selected
mx, my = self.parent.pixel_from_screen(x, y)
cell = m.get_at_pixel(mx, my)
#don't update if we haven't moved to a new cell
if cell is None or cell == self._current_cell:
return
cx, cy = sprite_key = cell.origin[:2]
self._current_cell = cell
x = cell.x
y = cell.y
self.highlight = (x, y, x+m.tw, y+m.th)
if self.tools.active_tool is 'pencil':
cell.tile = self.tiles.selected
m._sprites[sprite_key] = pyglet.sprite.Sprite(
cell.tile.image, x=cx, y=cy, batch=m.batch)
m._sprites[sprite_key].opacity = m.opacity
#m.set_dirty()
elif self.tools.active_tool is 'eraser':
if cell.tile is not None:
cell.tile = None
del m._sprites[sprite_key]
return True
def on_mouse_release(self, x, y, buttons, modifiers):
if self._dragging:
self._dragging = False
return False
def on_mouse_motion(self, x, y, dx, dy):
m = self.map_layers.selected
w = director.window
x, y = w._mouse_x, w._mouse_y
cell = m.get_at_pixel(*self.parent.pixel_from_screen(x, y))
if not cell:
self.highlight = None
return True
x = cell.x
y = cell.y
self.highlight = (x, y, x+m.tw, y+m.th)
return True
def draw(self):
if self.highlight is None:
return
if self.map_layers is not None:
glPushMatrix()
self.transform()
glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glColor4f(1, 1, 0, .3)
glRectf(*self.highlight)
glPopAttrib()
glPopMatrix()
class ScrollableColorLayer(cocos.layer.util_layers.ColorLayer,
tiles.ScrollableLayer):
def __init__(self, r,g,b,a, width=None, height=None):
super(ScrollableColorLayer, self).__init__(
r,g,b,a, width, height)
self.px_width, self.px_height = width, height
class Selector(list):
def __init__(self, lst):
super(Selector, self).__init__(lst)
self.selected = self[0]
def select(self, i):
self.selected = self[i]
class EditorScene(cocos.scene.Scene):
def __init__(self):
super(EditorScene, self).__init__()
self.manager = tiles.ScrollingManager()
self.add(self.manager)
self.dialog_layer = DialogLayer()
self.editor_layer = None
self.tool_dialog = ToolMenuDialog(director.window,
on_open=self.open)
self.tile_dialog = None
self.dialog_layer.add_dialog(self.tool_dialog)
self.add(self.dialog_layer)
def open(self, edit_level_xml):
# Clean up old dialogs
self.remove(self.manager)
self.manager = tiles.ScrollingManager()
if self.tile_dialog is not None:
self.tile_dialog.delete()
self.tool_dialog.delete()
self.remove(self.dialog_layer)
# Load level
#~ try:
level_to_edit = tiles.load(edit_level_xml)
#~ except:
#~ self.tool_dialog = ToolMenuDialog(director.window,
#~ on_open=self.open)
#~ return
#self.map_layers = level_to_edit.findall(tiles.MapLayer)
director.window.set_caption(edit_level_xml + " - " + VERSION)
# Setup map layers
mz = 0
for id, layer in level_to_edit.find(tiles.MapLayer):
self.manager.add(layer, z=layer.origin_z)
mz = max(layer.origin_z, mz)
# Copy z-sorted manager.children to selector
self.layer_selector = Selector(self.manager.get_children()[:])
bg_layer = ScrollableColorLayer(
255, 255, 255, 255,
width=self.layer_selector.selected.px_width,
height=self.layer_selector.selected.px_height)
self.manager.add(bg_layer, z=-999999)
# Setup new dialogs
self.tile_dialog = TilesetDialog(director.window, level_to_edit)
def on_resize(width, height):
self.tile_dialog.scrollable.max_width = width - 30
self.dialog_layer.on_resize = on_resize
def on_save():
level_to_edit.save_xml(edit_level_xml)
self.tool_dialog = ToolMenuDialog(
director.window,
on_open=self.open,
on_save=on_save,
map_layers=self.layer_selector,
level_to_edit=level_to_edit)
self.dialog_layer.add_dialog(self.tile_dialog)
self.dialog_layer.add_dialog(self.tool_dialog)
self.editor_layer = TileEditorLayer(
level_to_edit=level_to_edit,
tiles=self.tile_dialog,
map_layers=self.layer_selector,
tools=self.tool_dialog,
filename=edit_level_xml)
self.manager.add(self.editor_layer, z=mz+1)
self.add(self.manager)
# XXX if I don't remove and add the dlayer event handling is
# messed up...why?
self.add(self.dialog_layer, z=mz+2)
def edit_complete(self, layer):
pyglet.app.exit()
if __name__ == '__main__':
import sys
try:
edit_level_xml = sys.argv[1]
except IndexError:
edit_level_xml = None
except:
print 'Usage: %s <level.xml>'%sys.argv[0]
sys.exit(0)
director.init(width=800, height=600, resizable=True,
do_not_scale=True, caption=VERSION)
director.show_FPS = True
pyglet.gl.glClearColor(.3, .3, .3, 1)
e = EditorScene()
director.run(e)
if edit_level_xml is not None:
e.open(edit_level_xml)
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Grid data structure'''
__docformat__ = 'restructuredtext'
import pyglet
from pyglet import image
from pyglet.gl import *
from euclid import Point2, Point3
from director import director
import framegrabber
__all__ = ['GridBase',
'Grid3D',
'TiledGrid3D',
]
class GridBase(object):
"""
A Scene that takes two scenes and makes a transition between them
"""
texture = None
def __init__(self):
super(GridBase, self).__init__()
self._active = False
self.reuse_grid = 0 #! Number of times that this grid will be reused
def init( self, grid ):
'''Initializes the grid creating both a vertex_list for an independent-tiled grid
and creating also a vertex_list_indexed for a "united" (non independent tile) grid.
:Parameters:
`grid` : euclid.Point2
size of a 2D grid
'''
#: size of the grid. (rows, columns)
self.grid = grid
width, height = director.get_window_size()
if self.texture is None:
self.texture = image.Texture.create_for_size(
GL_TEXTURE_2D, width,
height, GL_RGBA)
self.grabber = framegrabber.TextureGrabber()
self.grabber.grab(self.texture)
#: x pixels between each vertex (float)
self.x_step = width / self.grid.x
#: y pixels between each vertex (float)
self.y_step = height / self.grid.y
self._init()
def before_draw( self ):
'''Binds the framebuffer to a texture
and set a 2d projection before binding
to prevent calculating a new texture
'''
self._set_2d_projection()
# capture before drawing
self.grabber.before_render(self.texture)
def after_draw( self, camera ):
'''Called by CocosNode when the texture is already grabbed.
The FrameBuffer will be unbound and the texture will be drawn
:Parameters:
`camera` : `Camera`
The target's camera object.
'''
# capture after drawing
self.grabber.after_render(self.texture)
# after unbinding
# set a 3d projection
self._set_3d_projection()
# and center the camera
camera.locate( force=True )
# blit
glEnable(self.texture.target)
glBindTexture(self.texture.target, self.texture.id)
glPushAttrib(GL_COLOR_BUFFER_BIT)
self._blit()
glPopAttrib()
glDisable(self.texture.target)
def _set_active(self, bool):
if self._active == bool:
return
self._active = bool
if self._active == True:
pass
elif self._active == False:
self.vertex_list.delete()
# to restore the camera to default position
director.set_projection()
else:
raise Exception("Invalid value for GridBase.active")
def _get_active(self):
return self._active
active = property(_get_active, _set_active,
doc='''Determines whether the grid is active or not
:type: bool
''')
def _init(self):
raise NotImplementedError('abstract')
def _blit(self):
raise NotImplementedError('abstract')
def _on_resize(self):
raise NotImplementedError('abstract')
@classmethod
def _set_3d_projection(cls):
glViewport(director._offset_x, director._offset_y, director._usable_width, director._usable_height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60, 1.0*director._usable_width/director._usable_height, 0.1, 3000.0)
glMatrixMode(GL_MODELVIEW)
@classmethod
def _set_2d_projection(cls):
# director.set_2d_projection()
width, height = director.get_window_size()
glLoadIdentity()
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, width, 0, height, -100, 100)
glMatrixMode(GL_MODELVIEW)
class Grid3D(GridBase):
'''`Grid3D` is a 3D grid implementation. Each vertex has 3 dimensions: x,y,z
The vindexed ertex array will be built with::
self.vertex_list.vertices: x,y,z (floats)
self.vertex_list.tex_coords: x,y,z (floats)
self.vertex_list.colors: RGBA, with values from 0 - 255
'''
def _init( self ):
# calculate vertex, textures depending on screen size
idx_pts, ver_pts_idx, tex_pts_idx = self._calculate_vertex_points()
#: indexed vertex array that can be transformed.
#: it has these attributes:
#:
#: - vertices
#: - colors
#: - tex_coords
#:
#: for more information refer to pyglet's documentation: pyglet.graphics.vertex_list_indexed
self.vertex_list = pyglet.graphics.vertex_list_indexed( (self.grid.x+1) * (self.grid.y+1),
idx_pts, "t2f", "v3f/stream","c4B")
#: original vertex array of the grid. (read-only)
self.vertex_points = ver_pts_idx[:]
self.vertex_list.vertices = ver_pts_idx
self.vertex_list.tex_coords = tex_pts_idx
self.vertex_list.colors = (255,255,255,255) * (self.grid.x+1) * (self.grid.y+1)
def _blit(self ):
self.vertex_list.draw(pyglet.gl.GL_TRIANGLES)
def _calculate_vertex_points(self):
w = float(self.texture.width)
h = float(self.texture.height)
index_points = []
vertex_points_idx = []
texture_points_idx = []
for x in xrange(0,self.grid.x+1):
for y in xrange(0,self.grid.y+1):
vertex_points_idx += [-1,-1,-1]
texture_points_idx += [-1,-1]
for x in xrange(0, self.grid.x):
for y in xrange(0, self.grid.y):
x1 = x * self.x_step
x2 = x1 + self.x_step
y1 = y * self.y_step
y2 = y1 + self.y_step
# d <-- c
# ^
# |
# a --> b
a = x * (self.grid.y+1) + y
b = (x+1) * (self.grid.y+1) + y
c = (x+1) * (self.grid.y+1) + (y+1)
d = x * (self.grid.y+1) + (y+1)
# 2 triangles: a-b-d, b-c-d
index_points += [ a, b, d, b, c, d] # triangles
l1 = ( a*3, b*3, c*3, d*3 )
l2 = ( Point3(x1,y1,0), Point3(x2,y1,0), Point3(x2,y2,0), Point3(x1,y2,0) )
# building the vertex
for i in xrange( len(l1) ):
vertex_points_idx[ l1[i] ] = l2[i].x
vertex_points_idx[ l1[i] + 1 ] = l2[i].y
vertex_points_idx[ l1[i] + 2 ] = l2[i].z
# building the texels
tex1 = ( a*2, b*2, c*2, d*2 )
tex2 = ( Point2(x1,y1), Point2(x2,y1), Point2(x2,y2), Point2(x1,y2) )
for i in xrange( len(tex1)):
texture_points_idx[ tex1[i] ] = tex2[i].x / w
texture_points_idx[ tex1[i] + 1 ] = tex2[i].y / h
return ( index_points, vertex_points_idx, texture_points_idx )
def get_vertex( self, x, y):
'''Get the current vertex coordinate
:Parameters:
`x` : int
x-vertex
`y` : int
y-vertex
:rtype: (float, float, float)
'''
idx = (x * (self.grid.y+1) + y) * 3
x = self.vertex_list.vertices[idx]
y = self.vertex_list.vertices[idx+1]
z = self.vertex_list.vertices[idx+2]
return (x,y,z)
def get_original_vertex( self, x, y):
'''Get the original vertex coordinate.
The original vertices are the ones weren't modified by the current action.
:Parameters:
`x` : int
x-vertex
`y` : int
y-vertex
:rtype: (float, float, float)
'''
idx = (x * (self.grid.y+1) + y) * 3
x = self.vertex_points[idx]
y = self.vertex_points[idx+1]
z = self.vertex_points[idx+2]
return (x,y,z)
def set_vertex( self, x, y, v):
'''Set a vertex point is a certain value
:Parameters:
`x` : int
x-vertex
`y` : int
y-vertex
`v` : (float, float, float)
tuple value for the vertex
'''
idx = (x * (self.grid.y+1) + y) * 3
self.vertex_list.vertices[idx] = int(v[0])
self.vertex_list.vertices[idx+1] = int(v[1])
self.vertex_list.vertices[idx+2] = int(v[2])
class TiledGrid3D(GridBase):
'''`TiledGrid3D` is a 3D grid implementation. It differs from `Grid3D` in that
the tiles can be separated from the grid.
The vertex array will be built with::
self.vertex_list.vertices: x,y,z (floats)
self.vertex_list.tex_coords: x,y (floats)
self.vertex_list.colors: RGBA, with values from 0 - 255
'''
def _init( self ):
# calculate vertex, textures depending on screen size
ver_pts, tex_pts = self._calculate_vertex_points()
#: vertex array that can be transformed.
#: it has these attributes:
#:
#: - vertices
#: - colors
#: - tex_coords
#:
#: for more information refer to pyglet's documentation: pyglet.graphics.vertex_list
self.vertex_list = pyglet.graphics.vertex_list(self.grid.x * self.grid.y * 4,
"t2f", "v3f/stream","c4B")
#: original vertex array of the grid. (read-only)
self.vertex_points = ver_pts[:]
self.vertex_list.vertices = ver_pts
self.vertex_list.tex_coords = tex_pts
self.vertex_list.colors = (255,255,255,255) * self.grid.x * self.grid.y * 4
def _blit(self ):
self.vertex_list.draw(pyglet.gl.GL_QUADS)
def _calculate_vertex_points(self):
w = float(self.texture.width)
h = float(self.texture.height)
vertex_points = []
texture_points = []
for x in xrange(0, self.grid.x):
for y in xrange(0, self.grid.y):
x1 = x * self.x_step
x2 = x1 + self.x_step
y1 = y * self.y_step
y2 = y1 + self.y_step
# Building the tiles' vertex and texture points
vertex_points += [x1, y1, 0, x2, y1, 0, x2, y2, 0, x1, y2, 0 ]
texture_points += [x1/w, y1/h, x2/w, y1/h, x2/w, y2/h, x1/w, y2/h]
# Generates a quad for each tile, to perform tiles effect
return (vertex_points, texture_points)
def set_tile(self, x, y, coords):
'''Set the 4 tile coordinates
Coordinates positions::
3 <-- 2
^
|
0 --> 1
:Parameters:
`x` : int
x coodinate of the tile
`y` : int
y coordinate of the tile
`coords` : [ float, float, float, float, float, float, float, float, float, float, float, float ]
The 4 coordinates in the format (x0, y0, z0, x1, y1, z1,..., x3, y3, z3)
'''
idx = (self.grid.y * x + y) * 4 * 3
self.vertex_list.vertices[idx:idx+12] = coords
def get_original_tile(self, x, y):
'''Get the 4-original tile coordinates.
Coordinates positions::
3 <-- 2
^
|
0 --> 1
:Parameters:
`x` : int
x coordinate of the tile
`y` : int
y coordinate of the tile
:rtype: [ float, float, float, float, float, float, float, float, float, float, float, float ]
:returns: The 4 coordinates with the following order: x0, y0, z0, x1, y1, z1,...,x3, y3, z3
'''
idx = (self.grid.y * x + y) * 4 * 3
return self.vertex_points[idx:idx+12]
def get_tile(self, x, y):
'''Get the current tile coordinates.
Coordinates positions::
3 <-- 2
^
|
0 --> 1
:Parameters:
`x` : int
x coordinate of the tile
`y` : int
y coordinate of the tile
:rtype: [ float, float, float, float, float, float, float, float, float, float, float, float ]
:returns: The 4 coordinates with the following order: x0, y0, z0, x1, y1, z1,...,x3, y3, z3
'''
idx = (self.grid.y * x + y) * 4 * 3
return self.vertex_list.vertices[idx:idx+12]
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
import cocosnode
import pyglet
from pyglet.gl import *
from euclid import *
import math
import copy
cuadric_t = '''
void main() {
vec2 pos = gl_TexCoord[0].st;
float res = pos.x*pos.x - pos.y;
if (res<0.0) {
gl_FragColor = gl_Color;
} else {
gl_FragColor = vec4(0.0,0.0,0.0,0.0);
}
}
'''
class Shader(object):
def __init__(self, source):
self.source = source
self.shader_no = glCreateShader(self.shader_type)
if not self.shader_no:
raise Exception("could not create shader")
prog = (c_char_p * 1)(source+chr(0))
length = (c_int * 1)(0)
glShaderSource(self.shader_no, 1,
cast(prog, POINTER(POINTER(c_char))),
cast(0, POINTER(c_int)))
glCompileShader(self.shader_no)
self.program_no = glCreateProgram()
if not self.program_no:
raise Exception("could not create program")
glAttachShader(self.program_no, self.shader_no)
glLinkProgram(self.program_no)
def begin(self):
glUseProgram(self.program_no)
def end(self):
glUseProgram(0)
class VertexShader(Shader):
shader_type = GL_VERTEX_SHADER
class FragmentShader(Shader):
shader_type = GL_FRAGMENT_SHADER
#cuadric = FragmentShader(cuadric_t)
__parameter_count = 0
def parameter(default=None):
global __parameter_count
name = str(__parameter_count)
__parameter_count+=1
def setter(self, value):
self._dirty = True
setattr(self, "_"+name, value)
def getter(self):
return getattr(self, "_"+name, default)
return property(getter, setter)
ROUND_CAP, SQUARE_CAP, BUTT_CAP = range(3)
MITER_JOIN, BEVEL_JOIN, ROUND_JOIN = range(3)
class Context(object):
def __init__(self):
self.color = 255,255,255,255
self.stroke_width = 2
self.cap = ROUND_CAP
self.join = ROUND_JOIN
self.transform = Matrix3()
def set_state(self):
glPushAttrib(GL_CURRENT_BIT|GL_LINE_BIT)
glColor4ub(*self.color)
glLineWidth(self.stroke_width)
def unset_state(self):
glPopAttrib()
def copy(self):
return copy.deepcopy(self)
def flatten(*args):
ret = []
for a in args:
for v in a:
ret.append( v )
return ret
class Segment:
def __init__(self, start, end, width):
self.start = Point2(*start)
self.end = Point2(*end)
self.width = width
self._tl = None
self._bl = None
self._tr = None
self._br = None
@property
def direction(self):
return Vector2( *(self.end-self.start)).normalized()
@property
def line_width(self):
return (
Matrix3.new_rotate(math.radians(90)) * self.direction *
(self.width / 2.0)
)
@property
def tl(self):
if self._tl: return self._tl
return self.end + self.line_width
@property
def tr(self):
if self._tr: return self._tr
return self.end - self.line_width
@property
def bl(self):
if self._bl: return self._bl
return self.start + self.line_width
@property
def br(self):
if self._br: return self._br
return self.start - self.line_width
@property
def left(self):
return LineSegment2( Point2(*self.bl), Point2(*self.tl) )
@property
def right(self):
return LineSegment2( Point2(*self.br), Point2(*self.tr) )
@property
def points(self):
return flatten( self.bl, self.br, self.tr, self.bl, self.tr, self.tl )
def reversed(self):
return Segment(self.end, self.start, self.width)
class Canvas(cocosnode.CocosNode):
def __init__(self):
super(Canvas, self).__init__()
self._dirty = True
self._color = 255,255,255,255
self._stroke_width = 1
self._parts = []
self._vertex_list = None
self._context = Context()
self._context_stack = []
self._texture = image = pyglet.resource.image('draw_texture.png').get_texture()
self._context_change = True
self._position = 0,0
def draw(self):
if self._dirty:
self._context = Context()
self._parts = []
self.free()
self.render()
self.build_vbo()
self._dirty = False
# set
glEnable(self._texture.target)
glBindTexture(self._texture.target, self._texture.id)
glPushAttrib(GL_COLOR_BUFFER_BIT)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glPushMatrix()
self.transform()
#cuadric.begin()
self._vertex_list.draw(GL_TRIANGLES)
#cuadric.end()
# unset
glPopMatrix()
glPopAttrib()
glDisable(self._texture.target)
def endcap(self, line, cap_type):
strip = []
texcoord = []
if cap_type == ROUND_CAP:
s = Segment( line.start,
line.start + (-line.direction) * line.width / 2,
line.width
)
strip.extend([int(x) for x in flatten(
s.bl, s.br, s.end,
s.br, s.tr, s.end,
s.bl, s.tl, s.end
)])
texcoord.extend([
0.1,0.9,0.1,0.5,0.5,0.9,
0,0,0.5,0,1,1,
0,0,0.5,0,1,1,
])
elif cap_type == SQUARE_CAP:
segment = Segment( line.start,
line.start + (-line.direction) * line.width / 2,
line.width
)
strip.extend([int(x) for x in segment.points])
texcoord.extend( flatten(*[ (0.1,0.9,0.1,0.5,0.5,0.9) for x in range(len(segment.points)/6) ]) )
return strip, texcoord
def build_vbo(self):
strip = []
colors = []
texcoord = []
for ctx, parts in self._parts:
start_len = len(strip)
for line in parts:
# build the line segments
last = line[0]
segments = []
for next in line[1:]:
segments.append( Segment( last, next, ctx.stroke_width ) )
last = next
# do we need caps?
if line[0] == line[-1]:
closed_path = True
else:
closed_path = False
# add caps
if not closed_path:
vertex, tex = self.endcap(segments[0], ctx.cap)
strip += vertex
texcoord += tex
vertex, tex = self.endcap(segments[-1].reversed(), ctx.cap)
strip += vertex
texcoord += tex
# update middle points
prev = None
for i, current in enumerate(segments):
# if not starting line
if ( prev ):
# turns left
inter = prev.left.intersect( current.left )
if inter:
prev._tl = inter
current._bl = inter
bottom = prev.tr
top = current.br
else:
inter = prev.right.intersect( current.right )
if inter:
prev._tr = inter
current._br = inter
bottom = prev.tl
top = current.bl
# add elbow
if ( prev and inter ):
if ctx.join == BEVEL_JOIN:
strip.extend( [ int(x) for x in
list(inter) + list(bottom) + list(top)
])
texcoord += [ 0.1,0.9,0.1,0.5,0.5,0.9 ]
elif ctx.join in (MITER_JOIN, ROUND_JOIN):
if bottom == top:
far = Point2(*bottom)
else:
far = Ray2(
Point2(*bottom), prev.direction
).intersect(Ray2(
Point2(*top), -current.direction
))
strip.extend( [ int(x) for x in
list(inter) + list(bottom) + list(top) +
list(bottom) + list(top) + list(far)
])
if ctx.join == ROUND_JOIN:
texcoord += [ 0.1,0.9,0.1,0.5,0.5,0.9, 0,0,1,1,0.5,0]
elif ctx.join == MITER_JOIN:
texcoord += [ 0.1,0.9,0.1,0.5,0.5,0.9,0.1,0.9,0.1,0.5,0.5,0.9 ]
# rotate values
prev = current
# add boxes for lines
for s in segments:
strip.extend( [ int(x) for x in s.points ] )
texcoord += flatten(*[ (0.1,0.9,0.1,0.5,0.5,0.9)
for x in range( len(s.points)/6)
])
colors.extend( list(ctx.color)*((len(strip)-start_len)/2) )
vertex_list = pyglet.graphics.vertex_list(len(strip)/2,
('v2i', strip),
('c4B', colors ),
('t2f', texcoord),
)
self._vertex_list = vertex_list
def on_exit(self):
self.free()
super(Canvas, self).on_exit()
def free(self):
self._dirty = True
if self._vertex_list:
self._vertex_list.delete()
self._vertex_list = None
def set_color(self, color):
self._context.color = color
self._context_change = True
def set_stroke_width(self, stroke_width):
self._context.stroke_width = stroke_width
self._context_change = True
def set_endcap(self, cap):
self._context.cap = cap
self._context_change = True
def set_join(self, join):
self._context.join = join
self._context_change = True
def rotate(self, radians):
self._context.transform.rotate( radians )
def translate(self, vect):
self._context.transform.translate( *vect )
def move_to(self, position):
self._position = self._context.transform * Point2(*position)
def line_to(self, end):
if self._context_change:
context, parts = self._context, [[self._position]]
self._parts.append((context, parts))
self._context = context.copy()
self._context_change = False
else:
context, parts = self._parts[-1]
end = self._context.transform * Point2(*end)
if parts[-1][-1] == self._position:
parts[-1].append( end )
else:
parts.append( [self._position, end] )
self._position = end
def push(self):
self._context_stack.append( self._context.copy() )
def pop(self):
self._context = self._context_stack.pop()
class Line(Canvas):
start = parameter()
end = parameter()
stroke_width = parameter()
color = parameter()
def __init__(self, start, end, color, stroke_width=1):
super(Line, self).__init__()
self.start = start
self.end = end
self.color = color
self.stroke_width = stroke_width
def render(self):
self.set_color( self.color )
self.set_stroke_width( self.stroke_width )
self.move_to( self.start )
self.line_to( self.end )
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008 Daniel Moisset, Ricardo Quesada, Rayentray Tappa, Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Transitions between Scenes'''
__docformat__ = 'restructuredtext'
import pyglet
from cocos.actions import *
import cocos.scene as scene
from cocos.director import director
from cocos.layer import ColorLayer
from cocos.sprite import Sprite
__all__ = [ 'TransitionScene',
'RotoZoomTransition','JumpZoomTransition',
'MoveInLTransition','MoveInRTransition',
'MoveInBTransition','MoveInTTransition',
'SlideInLTransition','SlideInRTransition',
'SlideInBTransition','SlideInTTransition',
'FlipX3DTransition', 'FlipY3DTransition','FlipAngular3DTransition',
'ShuffleTransition',
'TurnOffTilesTransition',
'FadeTRTransition', 'FadeBLTransition',
'FadeUpTransition', 'FadeDownTransition',
'ShrinkGrowTransition',
'CornerMoveTransition',
'EnvelopeTransition',
'SplitRowsTransition', 'SplitColsTransition',
'FadeTransition',
'ZoomTransition',
]
class TransitionScene(scene.Scene):
"""TransitionScene
A Scene that takes two scenes and makes a transition between them.
These scenes are children of the transition scene.
"""
def __init__(self, dst, duration=1.25, src=None):
'''Initializes the transition
:Parameters:
`dst` : Scene
Incoming scene
`duration` : float
Duration of the transition in seconds. Default: 1.25
`src` : Scene
Outgoing scene. Default: current scene
'''
super(TransitionScene, self).__init__()
self.in_scene = dst #: scene that will replace the old one
if src == None:
src = director.scene
# if the director is already running a transition scene then terminate
# it so we may move on
if isinstance(src, TransitionScene):
src.finish()
src = src.in_scene
self.out_scene = src #: scene that will be replaced
self.duration = duration #: duration in seconds of the transition
if not self.duration:
self.duration = 1.25
if self.out_scene is None:
raise Exception("You need to specfy a `src` argument")
if self.out_scene is self.in_scene:
raise Exception("Incoming scene must be different from outgoing scene")
self.start()
def start(self):
'''Adds the incoming scene with z=1 and the outgoing scene with z=0'''
self.add( self.in_scene, z=1 )
self.add( self.out_scene, z=0 )
def finish(self):
'''Called when the time is over.
It removes both the incoming and the outgoing scenes from the transition scene,
and restores the outgoing scene's attributes like: position, visible and scale.
'''
self.remove( self.in_scene )
self.remove( self.out_scene )
self.restore_out()
director.replace( self.in_scene )
def hide_out_show_in( self ):
'''Hides the outgoing scene and shows the incoming scene'''
self.in_scene.visible = True
self.out_scene.visible = False
def hide_all( self ):
'''Hides both the incoming and outgoing scenes'''
self.in_scene.visible = False
self.out_scene.visible = False
def restore_out( self ):
'''Restore the position, visible and scale attributes of the outgoing scene
to the original values'''
self.out_scene.visible = True
self.out_scene.position = (0,0)
self.out_scene.scale = 1
class RotoZoomTransition(TransitionScene):
'''Rotate and zoom out the outgoing scene, and then rotate and zoom in the incoming
'''
def __init__( self, *args, **kwargs ):
super(RotoZoomTransition, self ).__init__( *args, **kwargs)
width, height = director.get_window_size()
self.in_scene.scale = 0.001
self.out_scene.scale = 1.0
self.in_scene.transform_anchor = (width // 2, height //2 )
self.out_scene.transform_anchor = (width // 2, height //2 )
rotozoom = ( ScaleBy(0.001, duration=self.duration/2.0 ) | \
Rotate(360 * 2, duration=self.duration/2.0 ) ) + \
Delay( self.duration / 2.0 )
self.out_scene.do( rotozoom )
self.in_scene.do( Reverse(rotozoom) + CallFunc(self.finish) )
class JumpZoomTransition(TransitionScene):
'''Zoom out and jump the outgoing scene, and then jump and zoom in the incoming
'''
def __init__( self, *args, **kwargs ):
super(JumpZoomTransition, self ).__init__( *args, **kwargs)
width, height = director.get_window_size()
self.in_scene.scale = 0.5
self.in_scene.position = ( width, 0 )
self.in_scene.transform_anchor = (width // 2, height //2 )
self.out_scene.transform_anchor = (width // 2, height //2 )
jump = JumpBy( (-width,0), width//4, 2, duration=self.duration / 4.0 )
scalein = ScaleTo( 1, duration=self.duration / 4.0 )
scaleout = ScaleTo( 0.5, duration=self.duration / 4.0 )
jumpzoomout = scaleout + jump
jumpzoomin = jump + scalein
delay = Delay( self.duration / 2.0 )
self.out_scene.do( jumpzoomout )
self.in_scene.do( delay + jumpzoomin + CallFunc(self.finish) )
class MoveInLTransition(TransitionScene):
'''Move in from to the left the incoming scene.
'''
def __init__( self, *args, **kwargs ):
super(MoveInLTransition, self ).__init__( *args, **kwargs)
self.init()
a = self.get_action()
self.in_scene.do( (Accelerate(a,0.5) ) + CallFunc(self.finish) )
def init(self):
width, height = director.get_window_size()
self.in_scene.position=(-width,0)
def get_action(self):
return MoveTo( (0,0), duration=self.duration)
class MoveInRTransition(MoveInLTransition):
'''Move in from to the right the incoming scene.
'''
def init(self):
width, height = director.get_window_size()
self.in_scene.position=(width,0)
def get_action(self):
return MoveTo( (0,0), duration=self.duration)
class MoveInTTransition(MoveInLTransition):
'''Move in from to the top the incoming scene.
'''
def init(self):
width, height = director.get_window_size()
self.in_scene.position=(0,height)
def get_action(self):
return MoveTo( (0,0), duration=self.duration)
class MoveInBTransition(MoveInLTransition):
'''Move in from to the bottom the incoming scene.
'''
def init(self):
width, height = director.get_window_size()
self.in_scene.position=(0,-height)
def get_action(self):
return MoveTo( (0,0), duration=self.duration)
class SlideInLTransition(TransitionScene):
'''Slide in the incoming scene from the left border.
'''
def __init__( self, *args, **kwargs ):
super(SlideInLTransition, self ).__init__( *args, **kwargs)
self.width, self.height = director.get_window_size()
self.init()
move = self.get_action()
self.in_scene.do( Accelerate(move,0.5) )
self.out_scene.do( Accelerate(move,0.5) + CallFunc( self.finish) )
def init(self):
self.in_scene.position=( -self.width,0)
def get_action(self):
return MoveBy( (self.width,0), duration=self.duration)
class SlideInRTransition(SlideInLTransition):
'''Slide in the incoming scene from the right border.
'''
def init(self):
self.in_scene.position=(self.width,0)
def get_action(self):
return MoveBy( (-self.width,0), duration=self.duration)
class SlideInTTransition(SlideInLTransition):
'''Slide in the incoming scene from the top border.
'''
def init(self):
self.in_scene.position=(0,self.height)
def get_action(self):
return MoveBy( (0,-self.height), duration=self.duration)
class SlideInBTransition(SlideInLTransition):
'''Slide in the incoming scene from the bottom border.
'''
def init(self):
self.in_scene.position=(0,-self.height)
def get_action(self):
return MoveBy( (0,self.height), duration=self.duration)
class FlipX3DTransition(TransitionScene):
'''Flips the screen horizontally.
The front face is the outgoing scene and the back face is the incoming scene.
'''
def __init__( self, *args, **kwargs ):
super(FlipX3DTransition, self ).__init__( *args, **kwargs)
width, height = director.get_window_size()
turnongrid = Waves3D( amplitude=0, duration=0, grid=(1,1), waves=2 )
flip90 = OrbitCamera( angle_x=0, delta_z=90, duration = self.duration / 2.0 )
flipback90 = OrbitCamera( angle_x=0, angle_z=90, delta_z=90, duration = self.duration / 2.0 )
self.in_scene.visible = False
flip = turnongrid + \
flip90 + \
CallFunc(self.hide_all) + \
FlipX3D(duration=0) + \
CallFunc( self.hide_out_show_in ) + \
flipback90
self.do( flip + \
CallFunc(self.finish) + \
StopGrid() )
class FlipY3DTransition(TransitionScene):
'''Flips the screen vertically.
The front face is the outgoing scene and the back face is the incoming scene.
'''
def __init__( self, *args, **kwargs ):
super(FlipY3DTransition, self ).__init__( *args, **kwargs)
width, height = director.get_window_size()
turnongrid = Waves3D( amplitude=0, duration=0, grid=(1,1), waves=2 )
flip90 = OrbitCamera( angle_x=90, delta_z=-90, duration = self.duration / 2.0 )
flipback90 = OrbitCamera( angle_x=90, angle_z=90, delta_z=90, duration = self.duration / 2.0 )
self.in_scene.visible = False
flip = turnongrid + \
flip90 + \
CallFunc(self.hide_all) + \
FlipX3D(duration=0) + \
CallFunc( self.hide_out_show_in ) + \
flipback90
self.do( flip + \
CallFunc(self.finish) + \
StopGrid() )
class FlipAngular3DTransition(TransitionScene):
'''Flips the screen half horizontally and half vertically.
The front face is the outgoing scene and the back face is the incoming scene.
'''
def __init__( self, *args, **kwargs ):
super(FlipAngular3DTransition, self ).__init__( *args, **kwargs)
width, height = director.get_window_size()
turnongrid = Waves3D( amplitude=0, duration=0, grid=(1,1), waves=2 )
flip90 = OrbitCamera( angle_x=45, delta_z=90, duration = self.duration / 2.0 )
flipback90 = OrbitCamera( angle_x=45, angle_z=90, delta_z=90, duration = self.duration / 2.0 )
self.in_scene.visible = False
flip = turnongrid + \
flip90 + \
CallFunc(self.hide_all) + \
FlipX3D(duration=0) + \
CallFunc( self.hide_out_show_in ) + \
flipback90
self.do( flip + \
CallFunc(self.finish) + \
StopGrid() )
class ShuffleTransition(TransitionScene):
'''Shuffle the outgoing scene, and then reorder the tiles with the incoming scene.
'''
def __init__( self, *args, **kwargs ):
super(ShuffleTransition, self ).__init__( *args, **kwargs)
width, height = director.get_window_size()
aspect = width / float(height)
x,y = int(12*aspect), 12
shuffle = ShuffleTiles( grid=(x,y), duration=self.duration/2.0, seed=15 )
self.in_scene.visible = False
self.do( shuffle + \
CallFunc(self.hide_out_show_in) + \
Reverse(shuffle) + \
CallFunc(self.finish) + \
StopGrid()
)
class ShrinkGrowTransition(TransitionScene):
'''Shrink the outgoing scene while grow the incoming scene
'''
def __init__( self, *args, **kwargs ):
super(ShrinkGrowTransition, self ).__init__( *args, **kwargs)
width, height = director.get_window_size()
self.in_scene.scale = 0.001
self.out_scene.scale = 1
self.in_scene.transform_anchor = ( 2*width / 3.0, height / 2.0 )
self.out_scene.transform_anchor = ( width / 3.0, height / 2.0 )
scale_out = ScaleTo( 0.01, duration=self.duration )
scale_in = ScaleTo( 1.0, duration=self.duration )
self.in_scene.do( Accelerate(scale_in,0.5) )
self.out_scene.do( Accelerate(scale_out,0.5) + CallFunc( self.finish) )
class CornerMoveTransition(TransitionScene):
'''Moves the bottom-right corner of the incoming scene to the top-left corner
'''
def __init__( self, *args, **kwargs ):
super(CornerMoveTransition, self ).__init__( *args, **kwargs)
self.out_scene.do( MoveCornerUp( duration=self.duration ) + \
CallFunc(self.finish) + \
StopGrid() )
def start(self):
# don't call super. overriding order
self.add( self.in_scene, z=0 )
self.add( self.out_scene, z=1 )
class EnvelopeTransition(TransitionScene):
'''From the outgoing scene:
- moves the top-right corner to the center
- moves the bottom-left corner to the center
From the incoming scene:
- performs the reverse action of the outgoing scene
'''
def __init__( self, *args, **kwargs ):
super(EnvelopeTransition, self ).__init__( *args, **kwargs)
self.in_scene.visible = False
move = QuadMoveBy( delta0=(320,240), delta1=(-630,0), delta2=(-320,-240), delta3=(630,0), duration=self.duration / 2.0 )
# move = Accelerate( move )
self.do( move + \
CallFunc(self.hide_out_show_in) + \
Reverse(move) + \
CallFunc(self.finish) + \
StopGrid()
)
class FadeTRTransition(TransitionScene):
'''Fade the tiles of the outgoing scene from the left-bottom corner the to top-right corner.
'''
def __init__( self, *args, **kwargs ):
super(FadeTRTransition, self ).__init__( *args, **kwargs)
width, height = director.get_window_size()
aspect = width / float(height)
x,y = int(12*aspect), 12
a = self.get_action(x,y)
# a = Accelerate( a)
self.out_scene.do( a + \
CallFunc(self.finish) + \
StopGrid() )
def start(self):
# don't call super. overriding order
self.add( self.in_scene, z=0 )
self.add( self.out_scene, z=1 )
def get_action(self,x,y):
return FadeOutTRTiles( grid=(x,y), duration=self.duration )
class FadeBLTransition(FadeTRTransition):
'''Fade the tiles of the outgoing scene from the top-right corner to the bottom-left corner.
'''
def get_action(self,x,y):
return FadeOutBLTiles( grid=(x,y), duration=self.duration )
class FadeUpTransition(FadeTRTransition):
'''Fade the tiles of the outgoing scene from the bottom to the top.
'''
def get_action(self,x,y):
return FadeOutUpTiles( grid=(x,y), duration=self.duration )
class FadeDownTransition(FadeTRTransition):
'''Fade the tiles of the outgoing scene from the top to the bottom.
'''
def get_action(self,x,y):
return FadeOutDownTiles( grid=(x,y), duration=self.duration )
class TurnOffTilesTransition(TransitionScene):
'''Turn off the tiles of the outgoing scene in random order
'''
def __init__( self, *args, **kwargs ):
super(TurnOffTilesTransition, self ).__init__( *args, **kwargs)
width, height = director.get_window_size()
aspect = width / float(height)
x,y = int(12*aspect), 12
a = TurnOffTiles( grid=(x,y), duration=self.duration )
# a = Accelerate( a)
self.out_scene.do( a + \
CallFunc(self.finish) + \
StopGrid() )
def start(self):
# don't call super. overriding order
self.add( self.in_scene, z=0 )
self.add( self.out_scene, z=1 )
class FadeTransition(TransitionScene):
'''Fade out the outgoing scene and then fade in the incoming scene.
Optionally supply the color to fade to in-between as an RGB color tuple.
'''
def __init__( self, *args, **kwargs ):
color = kwargs.pop('color', (0, 0, 0)) + (0,)
super(FadeTransition, self ).__init__( *args, **kwargs)
self.fadelayer = ColorLayer(*color)
self.in_scene.visible = False
self.add( self.fadelayer, z=2 )
def on_enter( self ):
super( FadeTransition, self).on_enter()
self.fadelayer.do( FadeIn( duration=self.duration/2.0) + \
CallFunc( self.hide_out_show_in) + \
FadeOut( duration=self.duration /2.0 ) + \
CallFunc( self.finish) )
def on_exit( self ):
super( FadeTransition, self).on_exit()
self.remove( self.fadelayer )
class SplitColsTransition(TransitionScene):
'''Splits the screen in columns.
The odd columns goes upwards while the even columns goes downwards.
'''
def __init__( self, *args, **kwargs ):
super(SplitColsTransition, self ).__init__( *args, **kwargs)
width, height = director.get_window_size()
self.in_scene.visible = False
flip_a = self.get_action()
flip = flip_a + \
CallFunc( self.hide_out_show_in ) + \
Reverse(flip_a)
self.do( AccelDeccel(flip) + \
CallFunc(self.finish) + \
StopGrid() )
def get_action( self ):
return SplitCols( cols=3, duration=self.duration/2.0)
class SplitRowsTransition(SplitColsTransition):
'''Splits the screen in rows.
The odd rows goes to the left while the even rows goes to the right.
'''
def get_action( self ):
return SplitRows( rows=3, duration=self.duration/2.0)
class ZoomTransition(TransitionScene):
'''Zoom and FadeOut the outgoing scene.'''
def __init__(self, *args, **kwargs):
if 'src' in kwargs or len(args) == 3:
raise Exception("ZoomTransition does not accept 'src' parameter.")
super(ZoomTransition, self ).__init__( *args, **kwargs)
self.out_scene.visit()
def start(self):
screensprite = self._create_out_screenshot()
zoom = ScaleBy(2, self.duration) | FadeOut(self.duration)
screensprite.do(zoom)
restore = CallFunc(self.finish)
self.in_scene.do(Delay(self.duration * 2) + restore)
self.add(screensprite, z=1)
self.add(self.in_scene, z=0)
def finish(self):
'''Called when the time is over.
It removes both the incoming and the outgoing scenes from the transition scene,
and restores the outgoing scene's attributes like: position, visible and scale.
'''
self.remove( self.in_scene )
self.restore_out()
director.replace( self.in_scene )
def _create_out_screenshot(self):
# TODO: try to use `pyglet.image.get_buffer_manager().get_color_buffer()`
# instead of create a new BufferManager... note that pyglet uses
# a BufferManager singleton that fail when you change the window
# size.
buffer = pyglet.image.BufferManager()
image = buffer.get_color_buffer()
width, height = director.window.width, director.window.height
actual_width, actual_height = director.get_window_size()
out = Sprite(image)
out.position = actual_width / 2, actual_height / 2
out.scale = max(actual_width / float(width), actual_height / float(height))
return out
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Pause scene'''
__docformat__ = 'restructuredtext'
from cocos.director import director
from cocos.layer import Layer, ColorLayer
from cocos.scene import Scene
import pyglet
from pyglet.gl import *
__pause_scene_generator__ = None
def get_pause_scene():
return __pause_scene_generator__()
def set_pause_scene_generator(generator):
global __pause_scene_generator__
__pause_scene_generator__ = generator
def default_pause_scene():
w, h = director.window.width, director.window.height
texture = pyglet.image.Texture.create_for_size(
GL_TEXTURE_2D, w, h, GL_RGBA)
texture.blit_into(pyglet.image.get_buffer_manager().get_color_buffer(), 0,0,0)
return PauseScene(
texture.get_region(0, 0, w, h), ColorLayer(25,25,25,205), PauseLayer()
)
set_pause_scene_generator( default_pause_scene )
class PauseScene(Scene):
'''Pause Scene'''
def __init__(self, background, *layers):
super(PauseScene, self).__init__(*layers)
self.bg = background
self.width, self.height = director.get_window_size()
def draw(self):
self.bg.blit(0, 0, width=self.width, height=self.height)
super(PauseScene, self).draw()
class PauseLayer(Layer):
'''Layer that shows the text 'PAUSED'
'''
is_event_handler = True #: enable pyglet's events
def __init__(self):
super(PauseLayer, self).__init__()
x,y = director.get_window_size()
ft = pyglet.font.load('Arial', 36)
self.text = pyglet.font.Text(ft,
'PAUSED', halign=pyglet.font.Text.CENTER)
self.text.x = x/2
self.text.y = y/2
def draw(self):
self.text.draw()
def on_key_press(self, k, m):
if k == pyglet.window.key.P and m & pyglet.window.key.MOD_ACCEL:
director.pop()
return True
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
import pause
from transitions import *
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Implementation of TiledGrid3DAction actions
'''
__docformat__ = 'restructuredtext'
import random
from cocos.euclid import *
from basegrid_actions import *
from cocos.director import director
rr = random.randrange
__all__ = [ 'FadeOutTRTiles', # actions that don't modify the z coordinate
'FadeOutBLTiles',
'FadeOutUpTiles',
'FadeOutDownTiles',
'ShuffleTiles',
'TurnOffTiles',
'SplitRows',
'SplitCols',
'ShakyTiles3D', # actions that modify the z coordinate
'ShatteredTiles3D',
'WavesTiles3D',
'JumpTiles3D',
]
# Don't export this class
class Tile(object):
def __init__(self, position=(0,0), start_position=(0,0), delta=(0,0) ):
super(Tile,self).__init__()
self.position = position
self.start_position = start_position
self.delta = delta
def __repr__(self):
return "(start_pos: %s pos: %s delta:%s)" % (self.start_position, self.position, self.delta)
class ShakyTiles3D( TiledGrid3DAction ):
'''Simulates a shaky floor composed of tiles
Example::
scene.do( ShakyTiles3D( randrange=6, grid=(4,4), duration=10) )
'''
def init( self, randrange=6, *args, **kw ):
'''
:Parameters:
`randrange` : int
Number that will be used in random.randrange( -randrange, randrange) to do the effect
'''
super(ShakyTiles3D,self).init(*args,**kw)
self.randrange = randrange
def update( self, t ):
for i in xrange(0, self.grid.x):
for j in xrange(0, self.grid.y):
coords = self.get_original_tile(i,j)
for k in xrange(0,len(coords),3):
x = rr(-self.randrange, self.randrange+1)
y = rr(-self.randrange, self.randrange+1)
z = rr(-self.randrange, self.randrange+1)
coords[k] += x
coords[k+1] += y
coords[k+2] += z
self.set_tile(i,j,coords)
class ShatteredTiles3D( TiledGrid3DAction ):
'''ShatterTiles shatters the tiles according to a random value.
It is similar to shakes (see `ShakyTiles3D`) the tiles just one frame, and then continue with
that state for duration time.
Example::
scene.do( ShatteredTiles3D( randrange=12 ) )
'''
def init( self, randrange=6, *args, **kw ):
'''
:Parameters:
`randrange` : int
Number that will be used in random.randrange( -randrange, randrange) to do the effect
'''
super(ShatteredTiles3D,self).init(*args,**kw)
self.randrange = randrange
self._once = False
def update( self, t ):
if not self._once:
for i in xrange(0, self.grid.x):
for j in xrange(0, self.grid.y):
coords = self.get_original_tile(i,j)
for k in xrange(0,len(coords),3):
x = rr(-self.randrange, self.randrange+1)
y = rr(-self.randrange, self.randrange+1)
z = rr(-self.randrange, self.randrange+1)
coords[k] += x
coords[k+1] += y
coords[k+2] += z
self.set_tile(i,j,coords)
self._once = True
class ShuffleTiles( TiledGrid3DAction ):
'''ShuffleTiles moves the tiles randomly across the screen.
To put them back use: Reverse( ShuffleTiles() ) with the same seed parameter.
Example::
scene.do( ShuffleTiles( grid=(4,4), seed=1, duration=10) )
'''
def init(self, seed=-1, *args, **kw):
'''
:Parameters:
`seed` : float
Seed for the random in the shuffle.
'''
super(ShuffleTiles,self).init(*args, **kw)
self.seed = seed
def start(self):
super(ShuffleTiles,self).start()
self.tiles = {}
self._once = False
if self.seed != -1:
random.seed( self.seed )
# random positions
self.nr_of_tiles = self.grid.x * self.grid.y
self.tiles_order = range(self.nr_of_tiles )
random.shuffle( self.tiles_order )
for i in xrange(self.grid.x):
for j in xrange(self.grid.y):
self.tiles[(i,j)] = Tile( position = Point2(i,j),
start_position = Point2(i,j),
delta= self._get_delta(i,j) )
def place_tile(self, i, j):
t = self.tiles[(i,j)]
coords = self.get_original_tile(i,j)
for k in xrange(0,len(coords),3):
coords[k] += int( t.position.x * self.target.grid.x_step )
coords[k+1] += int( t.position.y * self.target.grid.y_step )
self.set_tile(i,j,coords)
def update(self, t ):
for i in xrange(0, self.grid.x):
for j in xrange(0, self.grid.y):
self.tiles[(i,j)].position = self.tiles[(i,j)].delta * t
self.place_tile(i,j)
# private method
def _get_delta(self, x, y):
idx = x * self.grid.y + y
i,j = divmod( self.tiles_order[idx], self.grid.y )
return Point2(i,j)-Point2(x,y)
class FadeOutTRTiles( TiledGrid3DAction ):
'''Fades out each tile following a diagonal Top-Right path until all the tiles are faded out.
Example::
scene.do( FadeOutTRTiles( grid=(16,12), duration=10) )
'''
def update( self, t ):
# direction right - up
for i in xrange(self.grid.x):
for j in xrange(self.grid.y):
distance = self.test_func(i,j,t)
if distance == 0:
self.turn_off_tile(i,j)
elif distance < 1:
self.transform_tile(i,j,distance)
else:
self.turn_on_tile(i,j)
def turn_on_tile(self, x,y):
self.set_tile(x,y, self.get_original_tile(x,y) )
def transform_tile(self, x, y, t ):
coords = self.get_original_tile(x,y)
for c in xrange( len(coords) ):
# x
if c == 0*3 or c == 3*3:
coords[c] = coords[c] + (self.target.grid.x_step / 2.0) * (1-t)
elif c == 1*3 or c == 2*3:
coords[c] = coords[c] - (self.target.grid.x_step / 2.0) * (1-t)
# y
if c == 0*3+1 or c == 1*3+1:
coords[c] = coords[c] + (self.target.grid.y_step / 2.0) * (1-t)
elif c == 2*3+1 or c == 3*3+1:
coords[c] = coords[c] - (self.target.grid.y_step / 2.0) * (1-t)
self.set_tile(x,y,coords)
def turn_off_tile( self,x,y):
self.set_tile(x,y,[0,0,0,0,0,0,0,0,0,0,0,0] )
def test_func(self, i,j, t ):
x,y = self.grid * t
if x+y==0:
return 1
return pow( (i+j) / float(x+y), 6 )
class FadeOutBLTiles( FadeOutTRTiles):
'''Fades out each tile following an Bottom-Left path until all the tiles are faded out.
Example::
scene.do( FadeOutBLTiles( grid=(16,12), duration=5) )
'''
def test_func(self, i,j,t):
x,y = self.grid * (1-t)
if i+j==0:
return 1
return pow( (x+y) / float(i+j), 6)
class FadeOutUpTiles( FadeOutTRTiles):
'''Fades out each tile following an upwards path until all the tiles are faded out.
Example::
scene.do( FadeOutUpTiles( grid=(16,12), duration=5) )
'''
def test_func(self, i,j, t):
x,y = self.grid * t
if y==0:
return 1
return pow( (j) / float(y), 6 )
def transform_tile(self, x, y, t ):
coords = self.get_original_tile(x,y)
for c in xrange( len(coords) ):
# y
if c == 0*3+1 or c == 1*3+1:
coords[c] = coords[c] + (self.target.grid.y_step / 2.0) * (1-t)
elif c == 2*3+1 or c == 3*3+1:
coords[c] = coords[c] - (self.target.grid.y_step / 2.0) * (1-t)
self.set_tile(x,y,coords)
class FadeOutDownTiles( FadeOutUpTiles):
'''Fades out each tile following an downwards path until all the tiles are faded out.
Example::
scene.do( FadeOutDownTiles( grid=(16,12), duration=5) )
'''
def test_func(self, i,j, t):
x,y = self.grid * (1-t)
if j==0:
return 1
return pow( (y) / float(j), 6 )
class TurnOffTiles( TiledGrid3DAction ):
'''TurnOffTiles turns off each in random order
Example::
scene.do( TurnOffTiles( grid=(16,12), seed=1, duration=10) )
'''
def init(self, seed=-1, *args, **kw):
super(TurnOffTiles,self).init( *args, **kw )
self.seed = seed
def start(self):
super(TurnOffTiles,self).start()
if self.seed != -1:
random.seed( self.seed )
self.nr_of_tiles = self.grid.x * self.grid.y
self.tiles_order = range(self.nr_of_tiles )
random.shuffle( self.tiles_order )
def update( self, t ):
l = int( t * self.nr_of_tiles )
for i in xrange( self.nr_of_tiles):
t = self.tiles_order[i]
if i < l:
self.turn_off_tile(t)
else:
self.turn_on_tile(t)
def get_tile_pos(self, idx):
return divmod(idx, self.grid.y)
def turn_on_tile(self, t):
x,y = self.get_tile_pos(t)
self.set_tile(x,y, self.get_original_tile(x,y) )
def turn_off_tile(self,t):
x,y = self.get_tile_pos(t)
self.set_tile(x,y,[0,0,0,0,0,0,0,0,0,0,0,0] )
class WavesTiles3D( TiledGrid3DAction ):
'''Simulates waves using the math.sin() function in the z-axis of each tile
Example::
scene.do( WavesTiles3D( waves=5, amplitude=120, grid=(16,16), duration=10) )
'''
def init( self, waves=4, amplitude=120, *args, **kw ):
'''
:Parameters:
`waves` : int
Number of waves (2 * pi) that the action will perform. Default is 4
`amplitude` : int
Wave amplitude (height). Default is 20
'''
super(WavesTiles3D, self).init( *args, **kw )
#: Total number of waves to perform
self.waves=waves
#: amplitude rate. Default: 1.0
#: This value is modified by other actions like `AccelAmplitude`.
self.amplitude_rate = 1.0
self.amplitude=amplitude
def update( self, t ):
for i in xrange(0, self.grid.x):
for j in xrange(0, self.grid.y):
coords = self.get_original_tile(i,j)
x = coords[0]
y = coords[1]
z = (math.sin(t*math.pi*self.waves*2 + (y+x) * .01) * self.amplitude * self.amplitude_rate )
for k in xrange( 0,len(coords),3 ):
coords[k+2] += z
self.set_tile( i,j, coords )
class JumpTiles3D( TiledGrid3DAction ):
'''Odd tiles will perform a jump in the z-axis using the sine function,
while the even tiles will perform a jump using sine+pi function
Example::
scene.do( JumpTiles3D( jumps=5, amplitude=40, grid=(16,16), duration=10) )
'''
def init( self, jumps=4, amplitude=20, *args, **kw ):
'''
:Parameters:
`jumps` : int
Number of jumps(2 * pi) that the action will perform. Default is 4
`amplitude` : int
Wave amplitude (height). Default is 20
'''
super(JumpTiles3D, self).init( *args, **kw )
#: Total number of jumps to perform
self.jumps=jumps
#: amplitude rate. Default: 1.0
#: This value is modified by other actions like `AccelAmplitude`.
self.amplitude_rate = 1.0
self.amplitude=amplitude
def update( self, t ):
sinz = (math.sin(t*math.pi*self.jumps*2 + (0) * .01) * self.amplitude * self.amplitude_rate )
sinz2= (math.sin(math.pi+t*math.pi*self.jumps*2 + (0) * .01) * self.amplitude * self.amplitude_rate )
for i in xrange(0, self.grid.x):
for j in xrange(0, self.grid.y):
coords = self.get_original_tile(i,j)
for k in xrange( 0,len(coords),3 ):
if (i+j) % 2 == 0:
coords[k+2] += sinz
else:
coords[k+2] += sinz2
self.set_tile( i,j, coords )
class SplitRows( TiledGrid3DAction ):
'''Split the screen in a number of rows, and move
these rows away from the screen.
The odds rows are moved to the left, while the even rows are moved to
the right.
Example::
scene.do( SplitRows( rows=3, duration=2) )
'''
def init( self, rows=9, grid=(-1,-1), *args, **kw ):
'''
:Parameters:
`rows` : int
Number of rows that will have the effect. Default: 9
'''
if grid != (-1,-1):
raise Exception("This action doesn't receives the grid argument")
grid = (1,rows)
self.rows = rows
super(SplitRows, self).init( grid, *args, **kw )
def update( self, t ):
x,y = director.get_window_size()
for j in xrange(0, self.grid.y):
coords = self.get_original_tile(0,j)
for c in xrange(0, len(coords), 3):
direction = 1
if j % 2 == 0:
direction = -1
coords[c] += direction * x * t
self.set_tile( 0,j, coords )
class SplitCols( TiledGrid3DAction ):
'''Split the screen in a number of columns, and move
these columns away from the screen.
The odds columns are moved to the upwards, while the even
columns are moved to the downwards.
Example::
scene.do( SplitCols( cols=3, duration=2) )
'''
def init( self, cols=9, grid=(-1,-1), *args, **kw ):
'''
:Parameters:
`cols` : int
Number of columns that will have the effect. Default: 9
'''
if grid != (-1,-1):
raise Exception("This action doesn't receives the grid argument")
grid = (cols,1)
self.cols = cols
super(SplitCols, self).init( grid, *args, **kw )
def update( self, t ):
x,y = director.get_window_size()
for i in xrange(0, self.grid.x):
coords = self.get_original_tile(i,0)
for c in xrange(0, len(coords), 3):
direction = 1
if i % 2 == 0:
direction = -1
coords[c+1] += direction * y * t
self.set_tile( i,0, coords )
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Grid Actions
Grid Actions
============
There are 2 kinds of grids:
- `Grid3D` : A 3D grid with x,y and z coordinates
- `TiledGrid3D` : A 3D grid with x,y and z coordinates, composed
with independent tiles
Hence, there are 2 kinds of grid actions:
- `Grid3DAction`
- `TiledGrid3DAction`
The `Grid3DAction` can modify any of vertex of the grid in any direction (x,y or z).
The `TiledGrid3DAction` can modify any tile of the grid without modifying the adjacent tiles.
To understand visually the difference between these 2 kinds of grids, try these examples:
- run ``test/test_shakytiles3d.py`` to see a `TiledGrid3DAction` example
- run ``test/test_shaky3d.py`` to see the `Grid3DAction` counterpart
'''
__docformat__ = 'restructuredtext'
from pyglet.gl import *
from cocos.grid import Grid3D, TiledGrid3D
from cocos.director import director
from cocos.euclid import *
from base_actions import *
__all__ = [ 'GridException', # Grid Exceptions
'GridBaseAction', # Base classes
'Grid3DAction',
'TiledGrid3DAction',
'AccelAmplitude', # Amplitude modifiers
'DeccelAmplitude',
'AccelDeccelAmplitude',
'StopGrid',
'ReuseGrid',
]
class GridException( Exception ):
pass
class GridBaseAction( IntervalAction ):
'''GridBaseAction is the base class of all Grid Actions.'''
def init( self, grid=(4,4), duration=5):
"""Initialize the Grid Action
:Parameters:
`grid` : (int,int)
Number of horizontal and vertical quads in the grid
`duration` : int
Number of seconds that the action will last
"""
self.duration = duration
if not isinstance(grid,Point2):
grid = Point2( *grid)
self.grid = grid
def start( self ):
new_grid = self.get_grid()
if self.target.grid and self.target.grid.reuse_grid > 0:
# Reusing the grid
if self.target.grid.active \
and self.grid == self.target.grid.grid \
and type(new_grid) == type(self.target.grid):
# since we are reusing the grid,
# we must "cheat" the action that the original vertex coords are
# the ones that were inhereted.
self.target.grid.vertex_points = self.target.grid.vertex_list.vertices[:]
self.target.grid.reuse_grid -= 1
self.target.grid.reuse_grid = max(0, self.target.grid.reuse_grid)
else:
# condition are not met
raise GridException("Cannot reuse grid. class grid or grid size did not match: %s vs %s and %s vs %s"
% ( str(self.grid), str(self.target.grid.grid), type(new_grid), type(self.target.grid) ) )
else:
# Not reusing the grid
if self.target.grid and self.target.grid.active:
self.target.grid.active = False
self.target.grid = new_grid
self.target.grid.init( self.grid )
self.target.grid.active = True
x,y = director.get_window_size()
self.size_x = x // self.grid.x
self.size_y = y // self.grid.y
def __reversed__(self):
return _ReverseTime(self)
class Grid3DAction( GridBaseAction ):
'''Action that does transformations
to a 3D grid ( `Grid3D` )'''
def get_grid(self):
return Grid3D()
def get_vertex( self, x, y):
'''Get the current vertex coordinate
:Parameters:
`x` : int
x-vertex
`y` : int
y-vertex
:rtype: (float, float, float)
'''
return self.target.grid.get_vertex(x,y)
def get_original_vertex( self, x, y):
'''Get the original vertex coordinate.
The original vertices are the ones weren't modified by the current action.
:Parameters:
`x` : int
x-vertex
`y` : int
y-vertex
:rtype: (float, float, float)
'''
return self.target.grid.get_original_vertex(x,y)
def set_vertex( self, x, y, v):
'''Set a vertex point is a certain value
:Parameters:
`x` : int
x-vertex
`y` : int
y-vertex
`v` : (float, float, float)
tuple value for the vertex
'''
return self.target.grid.set_vertex(x,y,v)
class TiledGrid3DAction( GridBaseAction ):
'''Action that does transformations
to a grid composed of tiles ( `TiledGrid3D` ).
You can transform each tile individually'''
def get_grid(self):
return TiledGrid3D()
def set_tile(self, x, y, coords):
'''Set the 4 tile coordinates
Coordinates positions::
3 <-- 2
^
|
0 --> 1
:Parameters:
`x` : int
x coodinate of the tile
`y` : int
y coordinate of the tile
`coords` : [ float, float, float, float, float, float, float, float, float, float, float, float ]
The 4 coordinates in the format (x0, y0, z0, x1, y1, z1,..., x3, y3, z3)
'''
return self.target.grid.set_tile(x,y,coords)
def get_original_tile(self, x, y):
'''Get the 4-original tile coordinates.
Coordinates positions::
3 <-- 2
^
|
0 --> 1
:Parameters:
`x` : int
x coordinate of the tile
`y` : int
y coordinate of the tile
:rtype: [ float, float, float, float, float, float, float, float, float, float, float, float ]
:returns: The 4 coordinates with the following order: x0, y0, z0, x1, y1, z1,...,x3, y3, z3
'''
return self.target.grid.get_original_tile(x,y)
def get_tile(self, x, y):
'''Get the current tile coordinates.
Coordinates positions::
3 <-- 2
^
|
0 --> 1
:Parameters:
`x` : int
x coordinate of the tile
`y` : int
y coordinate of the tile
:rtype: [ float, float, float, float, float, float, float, float, float, float, float, float ]
:returns: The 4 coordinates with the following order: x0, y0, z0, x1, y1, z1,...,x3, y3, z3
'''
return self.target.grid.get_tile(x,y)
class AccelDeccelAmplitude( IntervalAction ):
"""
Increases and Decreases the amplitude of Wave
Example::
# when t=0 and t=1 the amplitude will be 0
# when t=0.5 (half time), the amplitude will be 40
action = AccellDeccelAmplitude( Wave3D( waves=4, amplitude=40, duration=6) )
scene.do( action )
"""
def init(self, other, rate=1.0 ):
"""Init method.
:Parameters:
`other` : `IntervalAction`
The action that will be affected
`rate` : float
The acceleration rate. 1 is linear (default value)
"""
if not hasattr(other,'amplitude'):
raise GridAction("Invalid Composition: IncAmplitude needs an action with amplitude")
self.other = other
self.rate = rate
self.duration = other.duration
def start(self):
self.other.target = self.target
self.other.start()
def update(self, t):
f = t*2
if f > 1:
f -= 1
f = 1 -f
self.other.amplitude_rate = f**self.rate
self.other.update( t )
def __reversed__(self):
return AccelDeccelAmplitude( Reverse(self.other) )
class AccelAmplitude( IntervalAction ):
"""
Increases the waves amplitude from 0 to self.amplitude
Example::
# when t=0 the amplitude will be 0
# when t=1 the amplitude will be 40
action = AccelAmplitude( Wave3D( waves=4, amplitude=40, duration=6), rate=1.0 )
scene.do( action )
"""
def init(self, other, rate=1 ):
"""Init method.
:Parameters:
`other` : `IntervalAction`
The action that will be affected
`rate` : float
The acceleration rate. 1 is linear (default value)
"""
if not hasattr(other,'amplitude'):
raise GridAction("Invalid Composition: IncAmplitude needs an action with amplitude")
self.other = other
self.duration = other.duration
self.rate = rate
def start(self):
self.other.target = self.target
self.other.start()
def update(self, t):
self.other.amplitude_rate = (t ** self.rate)
self.other.update( t )
def __reversed__(self):
return DeccelAmplitude( Reverse(self.other), rate=self.rate )
class DeccelAmplitude( AccelAmplitude ):
"""
Decreases the waves amplitude from self.amplitude to 0
Example::
# when t=1 the amplitude will be 0
# when t=0 the amplitude will be 40
action = DeccelAmplitude( Wave3D( waves=4, amplitude=40, duration=6), rate=1.0 )
scene.do( action )
"""
def update(self, t):
self.other.amplitude_rate = ((1-t) ** self.rate)
self.other.update( t )
def __reversed__(self):
return AccelAmplitude( Reverse(self.other), rate=self.rate )
class StopGrid( InstantAction ):
"""StopGrid disables the current grid.
Every grid action, after finishing, leaves the screen with a certain grid figure.
This figure will be displayed until StopGrid or another Grid action is executed.
Example::
scene.do( Waves3D( duration=2) + StopGrid() )
"""
def start(self):
if self.target.grid and self.target.grid.active:
self.target.grid.active = False
class ReuseGrid( InstantAction ):
"""Will reuse the current grid for the next grid action.
The next grid action must have these properties:
- Be of the same class as the current one ( `Grid3D` or `TiledGrid3D` )
- Have the same size
If these condition are met, then the next grid action will receive as the ``original vertex``
or ``original tiles`` the current ones.
Example::
scene.do( Waves3D( duration=2) + ReuseGrid() + Lens3D(duration=2) )
"""
def init(self, reuse_times=1):
'''
:Parameters:
`reuse_times` : int
Number of times that the current grid will be reused by Grid actions. Default: 1
'''
self.reuse_times = reuse_times
def start(self):
if self.target.grid and self.target.grid.active:
self.target.grid.reuse_grid += self.reuse_times
else:
raise GridException("ReuseGrid must be used when a grid is still active")
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Interval Action
Interval Actions
================
An interval action is an action that takes place within a certain period of time.
It has an start time, and a finish time. The finish time is the parameter
``duration`` plus the start time.
These `IntervalAction` have some interesting properties, like:
- They can run normally (default)
- They can run reversed with the `Reverse` action.
- They can run with the time altered with the `Accelerate`, `AccelDeccel` and
`Speed` actions.
For example, you can simulate a Ping Pong effect running the action normally and
then running it again in Reverse mode.
Example::
ping_pong_action = action + Reverse( action )
Available IntervalActions
=========================
* `MoveTo`
* `MoveBy`
* `JumpTo`
* `JumpBy`
* `Bezier`
* `Blink`
* `RotateTo`
* `RotateBy`
* `ScaleTo`
* `ScaleBy`
* `FadeOut`
* `FadeIn`
* `FadeTo`
* `Delay`
* `RandomDelay`
Modifier actions
================
* `Accelerate`
* `AccelDeccel`
* `Speed`
Examples::
move = MoveBy( (200,0), duration=5 ) # Moves 200 pixels to the right in 5 seconds.
move = MoveTo( (320,240), duration=5) # Moves to the pixel (320,240) in 5 seconds
jump = JumpBy( (320,0), 100, 5, duration=5) # Jumps to the right 320 pixels
# doing 5 jumps of 100 pixels
# of height in 5 seconds
accel_move = Accelerate(move) # accelerates action move
'''
__docformat__ = 'restructuredtext'
import random
import copy
import math
from base_actions import *
from cocos.euclid import *
__all__ = [ 'Lerp', # interpolation
'MoveTo','MoveBy', # movement actions
'Jump', 'JumpTo', 'JumpBy',
'Bezier', # complex movement actions
'Rotate',"RotateTo", "RotateBy", # object rotation
'ScaleTo','ScaleBy', # object scale
'Delay','RandomDelay', # Delays
'FadeOut','FadeIn','FadeTo', # Fades in/out action
'Blink', # Blink action
'Accelerate','AccelDeccel','Speed', # Time alter actions
]
class Lerp( IntervalAction ):
"""
Interpolate between values for some specified attribute
"""
def init(self, attrib, start, end, duration):
"""Init method.
:Parameters:
`attrib` : string
The name of the attrbiute where the value is stored
`start` : float
The start value
`end` : float
The end value
`duration` : float
Duration time in seconds
"""
self.attrib = attrib
self.duration = duration
self.start_p = start
self.end_p = end
self.delta = end-start
def update(self, t):
setattr(self.target, self.attrib,
self.start_p + self.delta * t
)
def __reversed__(self):
return Lerp(self.attrib, self.end_p, self.start_p, self.duration)
class RotateBy( IntervalAction ):
"""Rotates a `CocosNode` object clockwise a number of degrees
by modiying it's rotation attribute.
Example::
# rotates the sprite 180 degrees in 2 seconds
action = RotateBy( 180, 2 )
sprite.do( action )
"""
def init(self, angle, duration ):
"""Init method.
:Parameters:
`angle` : float
Degrees that the sprite will be rotated.
Positive degrees rotates the sprite clockwise.
`duration` : float
Duration time in seconds
"""
self.angle = angle #: Quantity of degrees to rotate
self.duration = duration #: Duration in seconds
def start( self ):
self.start_angle = self.target.rotation
def update(self, t):
self.target.rotation = (self.start_angle + self.angle * t ) % 360
def __reversed__(self):
return RotateBy(-self.angle, self.duration)
Rotate = RotateBy
class RotateTo( IntervalAction ):
"""Rotates a `CocosNode` object to a certain angle by modifying it's
rotation attribute.
The direction will be decided by the shortest angle.
Example::
# rotates the sprite to angle 180 in 2 seconds
action = RotateTo( 180, 2 )
sprite.do( action )
"""
def init(self, angle, duration ):
"""Init method.
:Parameters:
`angle` : float
Destination angle in degrees.
`duration` : float
Duration time in seconds
"""
self.angle = angle%360 #: Destination angle in degrees
self.duration = duration #: Duration in seconds
def start( self ):
ea = self.angle
sa = self.start_angle = (self.target.rotation%360)
self.angle = ((ea%360) - (sa%360))
if self.angle > 180:
self.angle = -360+self.angle
if self.angle < -180:
self.angle = 360+self.angle
def update(self, t):
self.target.rotation = (self.start_angle + self.angle * t ) % 360
def __reversed__(self):
return RotateTo(-self.angle, self.duration)
class Speed( IntervalAction ):
"""
Changes the speed of an action, making it take longer (speed>1)
or less (speed<1)
Example::
# rotates the sprite 180 degrees in 1 secondclockwise
action = Speed( Rotate( 180, 2 ), 2 )
sprite.do( action )
"""
def init(self, other, speed ):
"""Init method.
:Parameters:
`other` : IntervalAction
The action that will be affected
`speed` : float
The speed change. 1 is no change.
2 means twice as fast, takes half the time
0.5 means half as fast, takes double the time
"""
self.other = other
self.speed = speed
self.duration = other.duration/speed
def start(self):
self.other.target = self.target
self.other.start()
def update(self, t):
self.other.update( t )
def __reversed__(self):
return Speed( Reverse( self.other ), self.speed )
class Accelerate( IntervalAction ):
"""
Changes the acceleration of an action
Example::
# rotates the sprite 180 degrees in 2 seconds clockwise
# it starts slow and ends fast
action = Accelerate( Rotate( 180, 2 ), 4 )
sprite.do( action )
"""
def init(self, other, rate = 2):
"""Init method.
:Parameters:
`other` : IntervalAction
The action that will be affected
`rate` : float
The acceleration rate. 1 is linear.
the new t is t**rate
"""
self.other = other
self.rate = rate
self.duration = other.duration
def start(self):
self.other.target = self.target
self.other.start()
def update(self, t):
self.other.update( t**self.rate )
def __reversed__(self):
return Accelerate(Reverse(self.other), 1.0/self.rate)
class AccelDeccel( IntervalAction ):
"""
Makes an action change the travel speed but retain near normal
speed at the beginning and ending.
Example::
# rotates the sprite 180 degrees in 2 seconds clockwise
# it starts slow, gets fast and ends slow
action = AccelDeccel( RotateBy( 180, 2 ) )
sprite.do( action )
"""
def init(self, other):
"""Init method.
:Parameters:
`other` : IntervalAction
The action that will be affected
"""
self.other = other
self.duration = other.duration
def start(self):
self.other.target = self.target
self.other.start()
def update(self, t):
ft = (t-0.5) * 12
nt = 1./( 1. + math.exp(-ft) )
self.other.update( nt )
def __reversed__(self):
return AccelDeccel( Reverse(self.other) )
class MoveTo( IntervalAction ):
"""Moves a `CocosNode` object to the position x,y. x and y are absolute coordinates
by modifying it's position attribute.
Example::
# Move the sprite to coords x=50, y=10 in 8 seconds
action = MoveTo( (50,10), 8 )
sprite.do( action )
"""
def init(self, dst_coords, duration=5):
"""Init method.
:Parameters:
`dst_coords` : (x,y)
Coordinates where the sprite will be placed at the end of the action
`duration` : float
Duration time in seconds
"""
self.end_position = Point2( *dst_coords )
self.duration = duration
def start( self ):
self.start_position = self.target.position
self.delta = self.end_position-self.start_position
def update(self,t):
self.target.position = self.start_position + self.delta * t
class MoveBy( MoveTo ):
"""Moves a `CocosNode` object x,y pixels by modifying it's
position attribute.
x and y are relative to the position of the object.
Duration is is seconds.
Example::
# Move the sprite 50 pixels to the left in 8 seconds
action = MoveBy( (-50,0), 8 )
sprite.do( action )
"""
def init(self, delta, duration=5):
"""Init method.
:Parameters:
`delta` : (x,y)
Delta coordinates
`duration` : float
Duration time in seconds
"""
self.delta = Point2( *delta )
self.duration = duration
def start( self ):
self.start_position = self.target.position
self.end_position = self.start_position + self.delta
def __reversed__(self):
return MoveBy(-self.delta, self.duration)
class FadeOut( IntervalAction ):
"""Fades out a `CocosNode` object by modifying it's opacity attribute.
Example::
action = FadeOut( 2 )
sprite.do( action )
"""
def init( self, duration ):
"""Init method.
:Parameters:
`duration` : float
Seconds that it will take to fade
"""
self.duration = duration
def update( self, t ):
self.target.opacity = 255 * (1-t)
def __reversed__(self):
return FadeIn( self.duration )
class FadeTo( IntervalAction ):
"""Fades a `CocosNode` object to a specific alpha value by modifying it's opacity attribute.
Example::
action = FadeTo( 128, 2 )
sprite.do( action )
"""
def init( self, alpha, duration ):
"""Init method.
:Parameters:
`alpha` : float
0-255 value of opacity
`duration` : float
Seconds that it will take to fade
"""
self.alpha = alpha
self.duration = duration
def start(self):
self.start_alpha = self.target.opacity
def update( self, t ):
self.target.opacity = self.start_alpha + (
self.alpha - self.start_alpha
) * t
class FadeIn( FadeOut):
"""Fades in a `CocosNode` object by modifying it's opacity attribute.
Example::
action = FadeIn( 2 )
sprite.do( action )
"""
def update( self, t ):
self.target.opacity = 255 * t
def __reversed__(self):
return FadeOut( self.duration )
class ScaleTo(IntervalAction):
"""Scales a `CocosNode` object to a zoom factor by modifying it's scale attribute.
Example::
# scales the sprite to 5x in 2 seconds
action = ScaleTo( 5, 2 )
sprite.do( action )
"""
def init(self, scale, duration=5 ):
"""Init method.
:Parameters:
`scale` : float
scale factor
`duration` : float
Duration time in seconds
"""
self.end_scale = scale
self.duration = duration
def start( self ):
self.start_scale = self.target.scale
self.delta = self.end_scale-self.start_scale
def update(self, t):
self.target.scale = self.start_scale + self.delta * t
class ScaleBy(ScaleTo):
"""Scales a `CocosNode` object a zoom factor by modifying it's scale attribute.
Example::
# scales the sprite by 5x in 2 seconds
action = ScaleBy( 5, 2 )
sprite.do( action )
"""
def start( self ):
self.start_scale = self.target.scale
self.delta = self.start_scale*self.end_scale - self.start_scale
def __reversed__(self):
return ScaleBy( 1.0/self.end_scale, self.duration )
class Blink( IntervalAction ):
"""Blinks a `CocosNode` object by modifying it's visible attribute
Example::
# Blinks 10 times in 2 seconds
action = Blink( 10, 2 )
sprite.do( action )
"""
def init(self, times, duration):
"""Init method.
:Parameters:
`times` : integer
Number of times to blink
`duration` : float
Duration time in seconds
"""
self.times = times
self.duration = duration
def update(self, t):
slice = 1 / float( self.times )
m = t % slice
self.target.visible = (m > slice / 2.0)
def __reversed__(self):
return self
class Bezier( IntervalAction ):
"""Moves a `CocosNode` object through a bezier path by modifying it's position attribute.
Example::
action = Bezier( bezier_conf.path1, 5 ) # Moves the sprite using the
sprite.do( action ) # bezier path 'bezier_conf.path1'
# in 5 seconds
"""
def init(self, bezier, duration=5, forward=True):
"""Init method
:Parameters:
`bezier` : bezier_configuration instance
A bezier configuration
`duration` : float
Duration time in seconds
"""
self.duration = duration
self.bezier = bezier
self.forward = forward
def start( self ):
self.start_position = self.target.position
def update(self,t):
if self.forward:
p = self.bezier.at( t )
else:
p = self.bezier.at( 1-t )
self.target.position = ( self.start_position +Point2( *p ) )
def __reversed__(self):
return Bezier(self.bezier, self.duration, not self.forward)
class Jump(IntervalAction):
"""Moves a `CocosNode` object simulating a jump movement by modifying it's position attribute.
Example::
action = Jump(50,200, 5, 6) # Move the sprite 200 pixels to the right
sprite.do( action ) # in 6 seconds, doing 5 jumps
# of 50 pixels of height
"""
def init(self, y=150, x=120, jumps=1, duration=5):
"""Init method
:Parameters:
`y` : integer
Height of jumps
`x` : integer
horizontal movement relative to the startin position
`jumps` : integer
quantity of jumps
`duration` : float
Duration time in seconds
"""
import warnings
warnings.warn('Deprecated "Jump" action. Consider using JumpBy instead', DeprecationWarning)
self.y = y
self.x = x
self.duration = duration
self.jumps = jumps
def start( self ):
self.start_position = self.target.position
def update(self, t):
y = int( self.y * abs( math.sin( t * math.pi * self.jumps ) ) )
x = self.x * t
self.target.position = self.start_position + Point2(x,y)
def __reversed__(self):
return Jump(self.y, -self.x, self.jumps, self.duration)
class JumpBy(IntervalAction):
"""Moves a `CocosNode` object simulating a jump movement by modifying it's position attribute.
Example::
# Move the sprite 200 pixels to the right and up
action = JumpBy((100,100),200, 5, 6)
sprite.do( action ) # in 6 seconds, doing 5 jumps
# of 200 pixels of height
"""
def init(self, position=(0,0), height=100, jumps=1, duration=5):
"""Init method
:Parameters:
`position` : integer x integer tuple
horizontal and vertical movement relative to the
starting position
`height` : integer
Height of jumps
`jumps` : integer
quantity of jumps
`duration` : float
Duration time in seconds
"""
self.position = position
self.height = height
self.duration = duration
self.jumps = jumps
def start( self ):
self.start_position = self.target.position
self.delta = Vector2(*self.position)
def update(self, t):
y = self.height * abs( math.sin( t * math.pi * self.jumps ) )
y = int(y+self.delta[1] * t)
x = self.delta[0] * t
self.target.position = self.start_position + Point2(x,y)
def __reversed__(self):
return JumpBy( (-self.position[0],-self.position[1]), self.height, self.jumps, self.duration)
class JumpTo(JumpBy):
"""Moves a `CocosNode` object to a position simulating a jump movement by modifying
it's position attribute.
Example::
action = JumpTo(50,200, 5, 6) # Move the sprite 200 pixels to the right
sprite.do( action ) # in 6 seconds, doing 5 jumps
# of 50 pixels of height
"""
def start( self ):
self.start_position = self.target.position
self.delta = Vector2(*self.position)-self.start_position
class Delay(IntervalAction):
"""Delays the action a certain amount of seconds
Example::
action = Delay(2.5)
sprite.do( action )
"""
def init(self, delay):
"""Init method
:Parameters:
`delay` : float
Seconds of delay
"""
self.duration = delay
def __reversed__(self):
return self
class RandomDelay(Delay):
"""Delays the actions between *min* and *max* seconds
Example::
action = RandomDelay(2.5, 4.5) # delays the action between 2.5 and 4.5 seconds
sprite.do( action )
"""
def init(self, low, hi):
"""Init method
:Parameters:
`low` : float
Minimun seconds of delay
`hi` : float
Maximun seconds of delay
"""
self.low = low
self.hi = hi
def __deepcopy__(self, memo):
new = copy.copy(self)
new.duration = self.low + (random.random() * (self.hi - self.low))
return new
def __mul__(self, other):
if not isinstance(other, int):
raise TypeError("Can only multiply actions by ints")
if other <= 1:
return self
return RandomDelay(low*other, hi*other)
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Foundation for all actions
Actions
=======
Actions purpose is to modify along the time some trait of an object.
The object that the action will modify is the action's target.
Usually the target will be an instance of some CocosNode subclass.
Example::
MoveTo(position, duration)
the target will move smoothly over the segment
(target.position, action position parameter), reaching the final position
after duration seconds have elapsed.
Cocos also provide some powerful operators to combine or modify actions, the
more important s being:
**sequence operator:** action_1 + action_2 -> action_result
where action_result performs by first doing all that action_1 would do and
then perform all that action_2 would do
Example use::
move_2 = MoveTo((100, 100), 10) + MoveTo((200, 200), 15)
When activated, move_2 will move the target first to (100, 100), it will
arrive there 10 seconds after departure; then it will move to (200, 200),
and will arrive there 10 seconds after having arrived to (100, 100)
**spawn operator:** action_1 | action_2 -> action_result
where action_result performs by doing what would do action_1 in parallel with
what would perform action_2
Example use::
move_rotate = MoveTo((100,100), 10) | RotateBy(360, 5)
When activated, move_rotate will move the target from the position at the
time of activation to (100, 100); also in the first 5 seconds target will
be rotated 360 degrees
**loop operator:** action_1 * n -> action_result
Where n non negative integer, and action result would repeat n times in a
row the same that action_1 would perform.
Example use::
rotate_3 = RotateBy(360, 5) * 3
When activated, rotate_3 will rotate target 3 times, spending 5 sec in each
turn.
Action instance roles
+++++++++++++++++++++
Action subclass: a detailed cualitative description for a change
An Action instance can play one of the following roles
Template Role
-------------
The instance knows all the details to perform,
except a target has not been set.
In this role only __init__ and init should be called.
It has no access to the concrete action target.
The most usual way to obtain an action in the template mode is
by calling the constructor of some Action subclass.
Example::
position = (100, 100); duration = 10
move = MoveTo(position, duration)
move is playing here the template role.
Worker role
-----------
Carry on with the changes desired when the action is initiated.
You obtain an action in the worker role by calling the method
do in a cocosnode instance, like::
worker_action = cocosnode.do(template_action, target=...)
The most usual is to call without the target kw-param, thus by default
setting target to the same cocosnode that performs the do.
The worker action begins to perform at the do call, and will carry on
with the desired modifications to target in subsequent frames.
If you want the capabilty to stop the changes midway, then you must
retain the worker_action returned by the do and then, when you want stop
the changes, call::
cocosnode.remove_action(worker_action)
( the cocosnode must be the same as in the do call )
Also, if your code need access to the action that performs the changes,
have in mind that you want the worker_action (but this is discouraged,
Example::
position = (100, 100); duration = 10
move = MoveTo(position, duration)
blue_bird = Bird_CocosNode_subclass(...)
blue_move = blue_bird.do(move)
Here move plays the template role and blue_move plays the worker role.
The target for blue_move has been set for the do method.
When the do call omits the target parameter it defaults to the cocosnode where
the do is called, so in the example the target for blue_move is blue_bird.
In subsequents frames after this call, the blue_bird will move to the position
(100, 100), arriving there 10 seconds after the do was executed.
From the point of view of a worker role action, the actions life
can be mimicked by::
worker_action = deepcopy(template_action)
worker_action.target = some_obj
worker_action.start()
for dt in frame.next():
worker_action.step(dt)
if premature_termination() or worker_action.done():
break
worker_action.stop()
Component role
--------------
Such an instance is created and stored into an Action class instance
that implements an Action operator (a composite action).
Carries on with the changes desired on behalf of the composite action.
When the composite action is not instance of IntervalAction, the
perceived life can be mimicked as in the worker role.
When the composite action is instance of IntervalAction, special rules apply.
For examples look at code used in the implementation of any operator, like
Sequence_Action or Sequence_IntervalAction.
Restrictions and Capabilities for the current design and implementation
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Worker Independence
-------------------
Multiple worker actions can be obtained from a single template action, and
they wont interfere between them when applied to different targets.
Example::
position = (100, 0); duration = 10
move = MoveBy(position, duration)
blue_bird = Sprite("blue_bird.png")
blue_bird.position = (0, 100)
blue_move = blue_bird.do(move)
red_bird = Sprite("red_bird.png")
red_bird.position = (0, 200)
red_move = blue_bird.do(move)
Here we placed two birds at the left screen border, separated vertically
by 100.
move is the template_action: full details on changes, still no target
blue_move, red_move are worker_action 's: obtained by a node.do, have all
the details plus the target; they will perform the changes along the time.
What we see is both birds moving smooth to right by 100, taking 10 seconds
to arrive at final position.
Note that even if both worker actions derive for the same template, they
don't interfere one with the other.
A worker action instance should not be used as a template
---------------------------------------------------------
You will not get tracebacks, but the second worker action most surelly will
have a corrupt workspace, that will produce unexpected behavior.
Posible fights between worker actions over a target member
----------------------------------------------------------
If two actions that are active at the same time try to change the same
target's member(s), the resulting change is computationally well defined, but
can be somewhat unexpected by the programmer.
Example::
guy = Sprite("grossini.png")
guy.position = (100, 100)
worker1 = guy.do(MoveTo((400, 100), 3))
worker2 = guy.do(MoveBy((0, 300), 3))
layer.add(guy)
Here the worker1 action will try to move to (400, 100), while the worker2 action
will try to move 300 in the up direction.
Both are changing guy.position in each frame.
What we see on screen, in the current cocos implementation, is the guy moving up,
like if only worker2 were active.
And, by physics, the programmer expectation probably guessed more like a
combination of both movements.
Note that the unexpected comes from two actions trying to control the same target
member. If the actions were changing diferent members, like position and
rotation, then no unexpected can happen.
The fighting can result in a behavior that is a combination of both workers, not one
a 'winning' one. It entirely depends on the implementation from each action.
It is possible to write actions than in a fight will show additive behavoir,
by example::
import cocos.euclid as eu
class MoveByAdditive(ac.Action):
def init( self, delta_pos, duration ):
try:
self.delta_pos = eu.Vector2(*delta_pos)/float(duration)
except ZeroDivisionError:
duration = 0.0
self.delta_pos = eu.Vector2(*delta_pos)
self.duration = duration
def start(self):
if self.duration==0.0:
self.target.position += self.delta_pos
self._done = True
def step(self, dt):
old_elapsed = self._elapsed
self._elapsed += dt
if self._elapsed > self.duration:
dt = self.duration - old_elapsed
self._done = True
self.target.position += dt*self.delta_pos
guy = Sprite("grossini.png")
guy.position = (100, 100)
worker1 = guy.do(MoveByAdditive((300, 0), 3))
worker2 = guy.do(MoveByAdditive((0, 300), 3))
layer.add(guy)
Here the guy will mode in diagonal, ending 300 right and 300 up, the two
actions have combined.
Action's instances in the template role must be (really) deepcopyiable
----------------------------------------------------------------------
Beginers note: if you pass in init only floats, ints, strings, dicts or tuples
of the former you can skip this section and revisit later.
If the action template is not deepcopyiable, you will get a deepcopy exception,
complaining it can't copy something
If you cheat deepcopy by overriding __deepcopy__ in your class like::
def __deepcopy__(self):
return self
you will not get a traceback, but the Worker Independence will broke, the Loop
and Repeat operators will broke, and maybe some more.
The section name states a precise requeriment, but it is a bit concise. Let see
some common situations where you can be in trouble and how to manage them.
- you try to pass a CocosNode instance in init, and init stores that in an
action member
- you try to pass a callback f = some_cocosnode.a_method, with the idea that
it shoud be called when some condition is meet, and init stores it in an
action member
- You want the action access some big decision table, static in the sense it
will not change over program execution. Even if is deepcopyable, there's
no need to deepcopy.
Workarounds:
- store the data that you do not want to deepcopy in some member in the
cocosnode
- use an init2 fuction to pass the params you want to not deepcopy::
worker = node.do(template)
worker.init2(another_cocosnode)
(see test_action_non_interval.py for an example)
Future:
Next cocos version probably will provide an easier mechanism to designate some
parameters as references.
Overview main subclasses
++++++++++++++++++++++++
All action classes in cocos must be subclass of one off the following:
- Action
- IntervalAction (is itself subclass of Action)
- InstantAction (is itself subclass of IntervalAction)
InstantAction
-------------
The task that must perform happens in only one call, the start method.
The duration member has the value zero.
Examples::
Place(position) : does target.position <- position
CallFunc(f, *args, **kwargs) : performs the call f(*args,**kwargs)
IntervalAction
--------------
The task that must perform is spanned over a number of frames.
The total time needed to complete the task is stored in the member duration.
The action will cease to perform when the time elapsed from the start call
reachs duration.
A proper IntervalAction must adhere to extra rules, look in the details section
Examples::
MoveTo(position, duration)
RotateBy(angle, duration)
Action
------
The most general posible action class.
The task that must perform is spanned over a number of frames.
The time that the action would perfom is undefined, and member duration has
value None.
Examples::
RandomWalk(fastness)
Performs:
- selects a random point in the screen
- moves to it with the required fastness
- repeat
This action will last forever.
::
Chase(fastness, chasee)
Performs:
- at each frame, move the target toward the chasee with the specified
fastness.
- Declare the action as done when the distance from target to
chasee is less than 10.
If fastness is greather than the chasee fastness this action will certainly
terminate, but we dont know how much time when the action starts.
'''
__docformat__ = 'restructuredtext'
import copy
__all__ = [
'Action', # Base Class
'IntervalAction', 'InstantAction', # Important Subclasses
'sequence','spawn','loop', 'Repeat',# Generic Operators
'Reverse','_ReverseTime', # Reverse
]
class Action(object):
'''The most general action'''
def __init__(self, *args, **kwargs):
"""dont override - use init"""
self.duration = None # The base action has potentially infinite duration
self.init(*args, **kwargs)
self.target = None #: `CocosNode` object that is the target of the action
self._elapsed = 0.0
self._done = False
self.scheduled_to_remove = False # exclusive use by cocosnode.remove_action
def init(*args, **kwargs):
"""
Gets called by __init__ with all the parameteres received,
At this time the target for the action is unknown.
Typical use is store parameters needed by the action.
"""
pass
def start(self):
"""
External code sets self.target and then calls this method.
Perform here any extra initialization needed.
"""
pass
def stop(self):
"""
When the action must cease to perform this function is called by
external code; after this call no other method should be called.
"""
self.target = None
def step(self, dt):
"""
Gets called every frame. `dt` is the number of seconds that elapsed
since the last call.
"""
self._elapsed += dt
def done(self):
"""
False while the step method must be called.
"""
return self._done
def __add__(self, action):
"""sequence operator - concatenates actions
action1 + action2 -> action_result
where action_result performs as:
first do all that action1 would do; then
perform all that action2 would do
"""
return sequence(self, action)
def __mul__(self, other):
"""repeats ntimes the action
action * n -> action_result
where action result performs as:
repeat n times the changes that action would do
"""
if not isinstance(other, int):
raise TypeError("Can only multiply actions by ints")
if other <= 1:
return self
return Loop_Action(self, other)
def __or__(self, action):
"""spawn operator - runs two actions in parallel
action1 | action2 -> action_result
"""
return spawn(self, action)
def __reversed__(self):
raise Exception("Action %s cannot be reversed"%(self.__class__.__name__))
class IntervalAction( Action ):
"""
IntervalAction()
Interval Actions are the ones that have fixed duration, known when the
worker instance is created, and, conceptually, the expected duration must
be positive.
Degeneratated cases, when a particular instance gets a zero duration, are
allowed for convenience.
IntervalAction adds the method update to the public interfase, and it
expreses the changes to target as a function of the time elapsed, relative
to the duration, ie f(time_elapsed/duration).
Also, it is guaranted that in normal termination .update(1.0) is called.
Degenerate cases, when a particular instance gets a zero duration, also
are guaranted to call .update(1.0)
Note that when a premature termination happens stop will be called but
update(1.0) is not called.
Examples: `MoveTo` , `MoveBy` , `RotateBy` are strictly Interval Actions,
while `Place`, `Show` and `CallFunc` aren't.
While
RotateBy(angle, duration) will usually receive a positive duration, it
will accept duration = 0, to ease on cases like
action = RotateBy( angle, a-b )
"""
def step(self, dt):
"""
Dont customize this method: it will not be called when in the component
role for certain composite actions (like Sequence_IntervalAction).
In such situation the composite will calculate the suitable t and
directly call .update(t)
You customize the action stepping by overriding .update
"""
self._elapsed += dt
try:
self.update( min(1, self._elapsed/self.duration ) )
except ZeroDivisionError:
self.update(1.0)
def update(self, t):
"""Gets called on every frame
't' is the time elapsed normalized to [0, 1]
If this action takes 5 seconds to execute, `t` will be equal to 0
at 0 seconds. `t` will be 0.5 at 2.5 seconds and `t` will be 1 at 5sec.
This method must not use self._elapsed, which is not guaranted to be
updated.
"""
pass
def done(self):
"""
When in the worker role, this method is reliable.
When in the component role, if the composite spares the call to
step this method cannot be relied (an then the composite must decide
by itself when the action is done).
Example of later situation is Sequence_IntervalAction.
"""
return self._elapsed >= self.duration
def __mul__(self, other):
if not isinstance(other, int):
raise TypeError("Can only multiply actions by ints")
if other <= 1:
return self
return Loop_IntervalAction(self, other)
def Reverse( action ):
"""Reverses the behavior of the action
Example::
# rotates the sprite 180 degrees in 2 seconds counter clockwise
action = Reverse( RotateBy( 180, 2 ) )
sprite.do( action )
"""
return action.__reversed__()
class InstantAction( IntervalAction ):
"""
Instant actions are actions that promises to do nothing when the
methods step, update, and stop are called.
Any changes that the action must perform on his target will be done in the
.start() method
The interface must be keept compatible with IntervalAction to allow the
basic operators to combine an InstantAction with an IntervalAction and
give an IntervalAction as a result.
"""
def __init__(self,*args, **kwargs):
super(IntervalAction, self).__init__(*args, **kwargs)
self.duration = 0.0
def step(self, dt):
"""does nothing - dont override"""
pass
def start(self):
"""
Here we must do out stuff
"""
pass
def done(self):
return True
def update(self, t):
"""does nothing - dont override
"""
pass
def stop(self):
"""does nothing - dont override
"""
pass
def __mul__(self, other):
if not isinstance(other, int):
raise TypeError("Can only multiply actions by ints")
if other <= 1:
return self
return Loop_InstantAction(self, other)
def loop(action, times):
return action * times
class Loop_Action(Action):
"""Repeats one Action for n times
"""
def init(self, one, times):
self.one = one
self.times = times
def start(self):
self.current_action = copy.deepcopy(self.one)
self.current_action.target = self.target
self.current_action.start()
def step(self, dt):
self._elapsed += dt
self.current_action.step(dt)
if self.current_action.done():
self.current_action.stop()
self.times -= 1
if self.times == 0:
self._done = True
else:
self.current_action = copy.deepcopy(self.one)
self.current_action.target = self.target
self.current_action.start()
def stop(self):
if not self._done:
self.current_action.stop()
class Loop_Instant_Action(InstantAction):
"""Repeats one InstantAction for n times
"""
def init(one, times):
self.one = one
self.times = times
def start(self):
for i in xrange(self.times):
cpy = copy.deepcopy(self.one)
cpy.start()
class Loop_IntervalAction(IntervalAction):
"""Repeats one IntervalAction for n times
"""
def init(self, one, times ):
"""Init method
:Parameters:
`one` : `Action`
Action to be repeated
`times` : int
Number of times that the action will be repeated
"""
self.one = one
self.times = times
if not hasattr(self.one, "duration"):
raise Exception("You can only loop actions with finite duration, not repeats or others like that")
self.duration = self.one.duration * times
self.current = None
self.last = None
def start(self):
self.duration = self.one.duration * self.times
self.last = 0
self.current_action = copy.deepcopy(self.one)
self.current_action.target = self.target
self.current_action.start()
def __repr__(self):
return "( %s * %i )" %( self.one, self.times )
def update(self, t):
current = int(t * float(self.times))
new_t = (t - (current * (1./self.times) ) ) * self.times
if current >= self.times: # we are done
return
# just more dt for the current action
elif current == self.last:
self.current_action.update(new_t)
else:
# finish the last action
self.current_action.update(1)
self.current_action.stop()
for i in range(self.last+1, current):
# fast forward the jumped actions
self.current_action = copy.deepcopy(self.one)
self.current_action.target = self.target
self.current_action.start()
self.current_action.update(1)
self.current_action.stop()
# set new current action
self.current_action = copy.deepcopy(self.one)
self.current_action.target = self.target
self.last = current
# start a new action
self.current_action.start()
# feed dt
self.current_action.update(new_t)
def stop(self):#todo: need to support early stop
self.current_action.update(1)
self.current_action.stop()
def __reversed__(self):
return Loop_IntervalAction( Reverse(self.one), self.times )
def sequence(action_1, action_2):
"""Returns an action that runs first action_1 and then action_2
The returned action will be instance of the most narrow class
posible in InstantAction, IntervalAction, Action
"""
if (isinstance(action_1,InstantAction) and
isinstance(action_2, InstantAction)):
cls = Sequence_InstantAction
elif (isinstance(action_1,IntervalAction) and
isinstance(action_2, IntervalAction)):
cls = Sequence_IntervalAction
else:
cls = Sequence_Action
return cls(action_1, action_2)
class Sequence_Action(Action):
"""implements sequence when the result cannot be expresed as IntervalAction
At least one operand must have duration==None """
def init(self, one, two, **kwargs ):
self.one = copy.deepcopy(one)
self.two = copy.deepcopy(two)
self.first = True
def start(self):
self.one.target = self.target
self.two.target = self.target
self.current_action = self.one
self.current_action.start()
def step(self, dt):
self._elapsed += dt
self.current_action.step(dt)
if self.current_action.done():
self._next_action()
def _next_action(self):
self.current_action.stop()
if self.first:
self.first = False
self.current_action = self.two
self.current_action.start()
if self.current_action.done():
self._done = True
else:
self.current_action = None
self._done = True
def stop(self):
if self.current_action:
self.current_action.stop()
def __reversed__(self):
return sequence( Reverse(self.two), Reverse(self.one) )
class Sequence_InstantAction(InstantAction):
"""implements sequence when the result can be expresed as InstantAction
both operands must be InstantActions """
def init(self, one, two, **kwargs ):
self.one = copy.deepcopy(one)
self.two = copy.deepcopy(two)
def start(self):
self.one.target = self.target
self.two.target = self.target
self.one.start()
self.two.start()
def __reversed__(self):
return Sequence_InstantAction( Reverse(self.two), Reverse(self.one) )
class Sequence_IntervalAction(IntervalAction):
"""implements sequence when the result can be expresed as IntervalAction but
not as InstantAction
"""
def init(self, one, two, **kwargs ):
"""Init method
:Parameters:
`one` : `Action`
The first action to execute
`two` : `Action`
The second action to execute
"""
self.one = copy.deepcopy(one)
self.two = copy.deepcopy(two)
self.actions = [self.one, self.two]
if not hasattr(self.one, "duration") or not hasattr(self.two, "duration"):
raise Exception("You can only sequence actions with finite duration, not repeats or others like that")
self.duration = float(self.one.duration + self.two.duration)
try:
self.split = self.one.duration / self.duration
except ZeroDivisionError:
self.split = 0.0
self.last = None
def start(self):
self.one.target = self.target
self.two.target = self.target
self.one.start()
self.last = 0 #index in self.actions
if self.one.duration==0.0:
self.one.update(1.0)
self.one.stop()
self.two.start()
self.last = 1
def __repr__(self):
return "( %s + %s )" %( self.one, self.two )
def update(self, t):
current = t>=self.split
if current!=self.last:
self.actions[self.last].update(1.0)
self.actions[self.last].stop()
self.last = current
self.actions[self.last].start()
if current==0:
try:
sub_t = t/self.split
except ZeroDivisionError:
sub_t = 1.0
else:
try:
sub_t = (t - self.split) / (1.0 - self.split)
except ZeroDivisionError:
sub_t = 1.0
self.actions[current].update(sub_t)
def stop(self):
if self.last:
self.two.stop()
else:
self.one.stop()
def __reversed__(self):
return Sequence_IntervalAction( Reverse(self.two), Reverse(self.one) )
def spawn(action_1, action_2):
"""Returns an action that runs action_1 and action_2 in paralel.
The returned action will be instance of the most narrow class
posible in InstantAction, IntervalAction, Action
"""
if (isinstance(action_1,InstantAction) and
isinstance(action_2, InstantAction)):
cls = Spawn_InstantAction
elif (isinstance(action_1,IntervalAction) and
isinstance(action_2, IntervalAction)):
cls = Spawn_IntervalAction
else:
cls = Spawn_Action
return cls(action_1, action_2)
class Spawn_Action(Action):
"""implements spawn when the result cannot be expresed as IntervalAction
At least one operand must have duration==None """
def init(self, one, two):
one = copy.deepcopy(one)
two = copy.deepcopy(two)
self.actions = [one, two]
def start(self):
for action in self.actions:
action.target = self.target
action.start()
def step(self, dt):
if len(self.actions)==2:
self.actions[0].step(dt)
if self.actions[0].done():
self.actions[0].stop()
self.actions = self.actions[1:]
if self.actions:
self.actions[-1].step(dt)
if self.actions[-1].done():
self.actions[-1].stop()
self.actions = self.actions[:-1]
self._done = len(self.actions)==0
def stop(self):
for e in self.actions:
print 'en el loop, name:', e.name
e.stop()
def __reversed__(self):
return Reverse( self.actions[0] ) | Reverse( self.actions[1] )
class Spawn_IntervalAction(IntervalAction):
"""implements spawn when the result cannot be expresed as InstantAction
"""
def init(self, one, two):
from cocos.actions.interval_actions import Delay
one = copy.deepcopy(one)
two = copy.deepcopy(two)
self.duration = max(one.duration, two.duration)
if one.duration > two.duration:
two = two + Delay( one.duration-two.duration )
elif two.duration > one.duration:
one = one + Delay( two.duration-one.duration )
self.actions = [one, two]
def start(self):
for a in self.actions:
a.target = self.target
a.start()
def update(self, t):
self.actions[0].update(t)
self.actions[1].update(t)
self._done = (t >= 1.0)
if self._done:
self.actions[0].stop()
self.actions[1].stop()
def __reversed__(self):
return Reverse( self.actions[0] ) | Reverse( self.actions[1] )
class Spawn_InstantAction(InstantAction):
"""implements spawn when the result can be expresed as InstantAction"""
def init(self, one, two):
one = copy.deepcopy(one)
two = copy.deepcopy(two)
self.actions = [one, two]
def start(self):
for action in self.actions:
action.target = self.target
action.start()
class Repeat(Action):
"""Repeats an action forever.
Applied to InstantAction s means once per frame.
Example::
action = JumpBy( (200,0), 50,3,5)
repeat = Repeat( action )
sprite.do( repeat )
Note: To repeat just a finite amount of time, just do action * times.
"""
def init(self, action):
"""Init method.
:Parameters:
`action` : `Action` instance
The action that will be repeated
"""
self.duration = None
self.original = action
self.action = copy.deepcopy( action )
def start(self):
self.action.target = self.target
self.action.start()
def step(self, dt):
self.action.step(dt)
if self.action.done():
self.action.stop()
self.action = copy.deepcopy(self.original)
self.start()
def done(self):
return False
class _ReverseTime( IntervalAction ):
"""Executes an action in reverse order, from time=duration to time=0
WARNING: Use this action carefully. This action is not
sequenceable. Use it as the default ``__reversed__`` method
of your own actions, but using it outside the ``__reversed``
scope is not recommended.
The default ``__reversed__`` method for all the `Grid3DAction` actions
and `Camera3DAction` actions is ``_ReverseTime()``.
"""
def init(self, other, *args, **kwargs):
super(_ReverseTime, self).init(*args, **kwargs)
self.other = other
self.duration = self.other.duration
def start(self):
self.other.target = self.target
super(_ReverseTime, self).start()
self.other.start()
def stop(self):
super(_ReverseTime,self).stop()
def update(self, t):
self.other.update(1-t)
def __reversed__(self):
return self.other
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Implementation of Grid3DAction actions
'''
__docformat__ = 'restructuredtext'
import math
import random
from cocos.director import director
from cocos.euclid import *
from basegrid_actions import *
rr = random.randrange
__all__ = [
'Waves3D', # 3d actions that modifies the z-coordinate
'FlipX3D',
'FlipY3D',
'Lens3D',
'Shaky3D',
'Ripple3D',
'Liquid', # 3d actions that don't modify the z-coordinate
'Waves',
'Twirl',
]
class Waves3D( Grid3DAction ):
'''Simulates waves using the math.sin() function in the z-axis
The x and y coordinates remains unmodified.
Example::
scene.do( Waves3D( waves=5, amplitude=40, grid=(16,16), duration=10) )
'''
def init( self, waves=4, amplitude=20, *args, **kw ):
'''
:Parameters:
`waves` : int
Number of waves (2 * pi) that the action will perform. Default is 4
`amplitude` : int
Wave amplitude (height). Default is 20
'''
super(Waves3D, self).init( *args, **kw )
#: Total number of waves to perform
self.waves=waves
#: amplitude rate. Default: 1.0.
#: This value is modified by other actions like `AccelAmplitude`.
self.amplitude_rate = 1.0
self.amplitude=amplitude
def update( self, t ):
for i in xrange(0, self.grid.x+1):
for j in xrange(0, self.grid.y+1):
x,y,z = self.get_original_vertex(i,j)
z += (math.sin(t*math.pi*self.waves*2 + (y+x) * .01) * self.amplitude * self.amplitude_rate )
self.set_vertex( i,j, (x, y, z) )
class FlipX3D( Grid3DAction ):
'''FlipX3D flips the screen using the Y-axis as a pivot.'''
def init(self, grid=(1,1), *args, **kw):
if grid != (1,1):
raise GridException("Invalid grid size.")
super(FlipX3D,self).init(grid=grid,*args,**kw)
def update( self, t ):
angle = math.pi * t # 180 degrees
mz = math.sin( angle )
angle = angle / 2.0 # x calculates degrees from 0 to 90
mx = math.cos( angle )
x0,y,z = self.get_original_vertex(1,1)
x1,y,z = self.get_original_vertex(0,0)
if x0 > x1:
# Normal Grid
a = (0,0)
b = (0,1)
c = (1,0)
d = (1,1)
x = x0
else:
# Reversed Grid
c = (0,0)
d = (0,1)
a = (1,0)
b = (1,1)
x = x1
diff_x = x - x * mx
diff_z = abs( (x * mz) // 4.0 )
# bottom-left
x,y,z = self.get_original_vertex(*a)
self.set_vertex(a[0],a[1],(diff_x,y,z+diff_z))
# upper-left
x,y,z = self.get_original_vertex(*b)
self.set_vertex(b[0],b[1],(diff_x,y,z+diff_z))
# bottom-right
x,y,z = self.get_original_vertex(*c)
self.set_vertex(c[0],c[1],(x-diff_x,y,z-diff_z))
# upper-right
x,y,z = self.get_original_vertex(*d)
self.set_vertex(d[0],d[1],(x-diff_x,y,z-diff_z))
class FlipY3D( Grid3DAction ):
'''FlipY3D flips the screen using the X-axis as a pivot.'''
def init(self, grid=(1,1), *args, **kw):
if grid != (1,1):
raise GridException("Invalid grid size.")
super(FlipY3D,self).init(grid=grid,*args,**kw)
def update( self, t ):
angle = math.pi * t # 180 degrees
mz = math.sin( angle )
angle = angle / 2.0 # x calculates degrees from 0 to 90
my = math.cos( angle )
x,y0,z = self.get_original_vertex(1,1)
x,y1,z = self.get_original_vertex(0,0)
if y0 > y1:
# Normal Grid
a = (0,0)
b = (0,1)
c = (1,0)
d = (1,1)
y = y0
else:
# Reversed Grid
b = (0,0)
a = (0,1)
d = (1,0)
c = (1,1)
y = y1
diff_y = y - y * my
diff_z = abs( (y * mz) // 4.0 )
# bottom-left
x,y,z = self.get_original_vertex(*a)
self.set_vertex(a[0],a[1],(x,diff_y,z+diff_z))
# upper-left
x,y,z = self.get_original_vertex(*b)
self.set_vertex(b[0],b[1],(x,y-diff_y,z-diff_z))
# bottom-right
x,y,z = self.get_original_vertex(*c)
self.set_vertex(c[0],c[1],(x,diff_y,z+diff_z))
# upper-right
x,y,z = self.get_original_vertex(*d)
self.set_vertex(d[0],d[1],(x,y-diff_y,z-diff_z))
class Lens3D( Grid3DAction ):
'''Lens simulates a Lens / Magnifying glass effect.
It modifies the z-coordinate while the x and y remains unmodified.
Example::
scene.do( Lens3D(center=(320,240), radius=150, grid=(16,16), duration=10) )
'''
def init(self, center=(-1,-1), radius=160, lens_effect=0.7, *args, **kw):
'''
:Parameters:
`center` : (int,int)
Center of the lens. Default: (win_size_width /2, win_size_height /2 )
`radius` : int
Radius of the lens.
`lens_effect` : float
How strong is the lens effect. Default: 0.7. 0 is no effect at all, 1 is a very strong lens effect.
'''
super(Lens3D,self).init( *args, **kw)
x,y = director.get_window_size()
if center==(-1,-1):
center=(x//2, y//2)
#: position of the center of the len. Type: (int,int).
#: This value can be modified by other actions, like `JumpBy` to simulate a jumping lens
self.position = Point2( center[0]+1, center[1]+1 )
#: radius of the lens. Type: float
self.radius = radius
#: lens effect factor. Type: float
self.lens_effect = lens_effect
self._last_position = (-1000,-1000) # dirty vrbl
def update( self, t ):
if self.position != self._last_position:
for i in xrange(0, self.grid.x+1):
for j in xrange(0, self.grid.y+1):
x,y,z = self.get_original_vertex(i,j)
p = Point2( x,y )
vect = self.position - p
r = abs(vect)
if r < self.radius:
r = self.radius - r
pre_log = r/self.radius
if pre_log == 0:
pre_log = 0.001
l = math.log( pre_log )*self.lens_effect
new_r = math.exp( l ) * self.radius
vect.normalize()
new_vect = vect * new_r
z += abs(new_vect) * self.lens_effect # magic vrbl
# set all vertex, not only the on the changed
# since we want to 'fix' possible moved vertex
self.set_vertex( i,j, (x,y,z) )
self._last_position = self.position
class Ripple3D( Grid3DAction ):
'''Simulates a ripple (radial wave) effect.
The amplitude of the wave will decrease when it goes away from the center of the ripple.
It modifies the z-coordinate while the x and y remains unmodified.
Example::
scene.do( Ripple3D(center=(320,240), radius=240, waves=15, amplitude=60, duration=20, grid=(32,24) ) )
'''
def init(self, center=(-1,-1), radius=240, waves=15, amplitude=60, *args, **kw):
'''
:Parameters:
`center` : (int,int)
Center of the ripple. Default: (win_size_width /2, win_size_height /2 )
`radius` : int
Radius of the ripple. Default: 240
`waves` : int
Number of waves (2 * pi) that the action will perform. Default: 15
`amplitude` : int
Wave amplitude (height). Default is 60
'''
super(Ripple3D,self).init( *args, **kw)
x,y = director.get_window_size()
if center==(-1,-1):
center=(x//2, y//2)
#: Center of the ripple. Type: (int,int).
#: This value can be modified by other actions, like `JumpBy` to simulate a jumping ripple effect
self.position = Point2( center[0]+1, center[1]+1 )
#: radius of the ripple. Type: float
self.radius = radius
#: number of waves. Type: int
self.waves = waves
#: amplitude rate. Default: 1.0.
#: This value is modified by other actions like `AccelAmplitude`.
self.amplitude_rate = 1.0
self.amplitude=amplitude
def update( self, t ):
for i in xrange(0, self.grid.x+1):
for j in xrange(0, self.grid.y+1):
x,y,z = self.get_original_vertex(i,j)
p = Point2( x,y )
vect = self.position - p
r = abs(vect)
if r < self.radius:
r = self.radius - r
rate = pow( r / self.radius, 2)
z += (math.sin( t*math.pi*self.waves*2 + r * 0.1) * self.amplitude * self.amplitude_rate * rate )
self.set_vertex( i,j, (x,y,z) )
class Shaky3D( Grid3DAction):
'''Shaky simulates an earthquake by modifying randomly the x, y and z coordinates of each vertex.
Example::
scene.do( Shaky3D( randrange=6, grid=(4,4), duration=10) )
'''
def init( self, randrange=6, *args, **kw ):
'''
:Parameters:
`randrange` : int
Number that will be used in random.randrange( -randrange, randrange) to do the effect
'''
super(Shaky3D,self).init(*args,**kw)
#: random range of the shaky effect
self.randrange = randrange
def update( self, t ):
for i in xrange(0, self.grid.x+1):
for j in xrange(0, self.grid.y+1):
x,y,z = self.get_original_vertex(i,j)
x += rr( -self.randrange, self.randrange+1 )
y += rr( -self.randrange, self.randrange+1 )
z += rr( -self.randrange, self.randrange+1 )
self.set_vertex( i,j, (x,y,z) )
class Liquid( Grid3DAction ):
'''Simulates a liquid effect using the math.sin() function modifying the x and y coordinates.
The z coordinate remains unmodified.
Example::
scene.do( Liquid( waves=5, amplitude=40, grid=(16,16), duration=10) )
'''
def init( self, waves=4, amplitude=20, *args, **kw ):
'''
:Parameters:
`waves` : int
Number of waves (2 * pi) that the action will perform. Default is 4
`amplitude` : int
Wave amplitude (height). Default is 20
'''
super(Liquid, self).init( *args, **kw )
#: total number of waves
self.waves=waves
#: amplitude of the waves
self.amplitude=amplitude
#: amplitude rate. Default: 1.0.
#: This value is modified by other actions like `AccelAmplitude`.
self.amplitude_rate = 1.0
def update( self, t ):
for i in xrange(1, self.grid.x):
for j in xrange(1, self.grid.y):
x,y,z = self.get_original_vertex(i,j)
xpos = (x + (math.sin(t*math.pi*self.waves*2 + x * .01) * self.amplitude * self.amplitude_rate))
ypos = (y + (math.sin(t*math.pi*self.waves*2 + y * .01) * self.amplitude * self.amplitude_rate))
self.set_vertex( i,j, (xpos,ypos,z) )
class Waves( Grid3DAction ):
'''Simulates waves using the math.sin() function both in the vertical and horizontal axis.
The z coordinate is not modified.
Example::
scene.do( Waves( waves=4, amplitude=20, hsin=False, vsin=True, grid=(16,16), duration=10) )
'''
def init( self, waves=4, amplitude=20, hsin=True, vsin=True, *args, **kw ):
'''Initializes the Waves actions
:Parameters:
`waves` : int
Number of waves (2 * pi) that the action will perform. Default is 4
`amplitude` : int
Wave amplitude (height). Default is 20
`hsin` : bool
whether or not in will perform horizontal waves. Default is True
`vsin` : bool
whether or not in will perform vertical waves. Default is True
'''
super(Waves, self).init( *args, **kw )
#: whether or not it will do horizontal waves
self.hsin = hsin
#: whether or not it will do vertical waves
self.vsin = vsin
#: total number of wave
self.waves=waves
#: amplitude of the waves
self.amplitude=amplitude
#: amplitude rate. Default: 1.0
#: This value is modified by other actions like `AccelAmplitude`.
self.amplitude_rate = 1.0
def update( self, t ):
for i in xrange(0, self.grid.x+1):
for j in xrange(0, self.grid.y+1):
x,y,z = self.get_original_vertex(i,j)
if self.vsin:
xpos = (x + (math.sin(t*math.pi*self.waves*2 + y * .01) * self.amplitude * self.amplitude_rate))
else:
xpos = x
if self.hsin:
ypos = (y + (math.sin(t*math.pi*self.waves*2 + x * .01) * self.amplitude * self.amplitude_rate))
else:
ypos = y
self.set_vertex( i,j, (xpos,ypos,z) )
class Twirl( Grid3DAction ):
'''Simulates a twirl effect modifying the x and y coordinates.
The z coordinate is not modified.
Example::
scene.do( Twirl( center=(320,240), twirls=5, amplitude=1, grid=(16,12), duration=10) )
'''
def init( self, center=(-1,-1), twirls=4, amplitude=1, *args, **kw ):
'''
:Parameters:
`twirls` : int
Number of twirls (2 * pi) that the action will perform. Default is 4
`amplitude` : flaot
Twirl amplitude. Default is 1
`center` : (int,int)
Center of the twirl in x,y coordinates. Default: center of the screen
'''
super(Twirl, self).init( *args, **kw )
x,y = director.get_window_size()
if center==(-1,-1):
center=(x//2, y//2)
#: position of the center of the Twril. Type: (int,int).
#: This value can be modified by other actions, like `JumpBy` to simulate a jumping Twirl
self.position = Point2( center[0]+1, center[1]+1 )
#: total number of twirls
self.twirls = twirls
#: amplitude of the twirls
self.amplitude=amplitude
#: amplitude rate. Default: 1.0.
#: This value is modified by other actions like `AccelAmplitude`.
self.amplitude_rate = 1.0
def update( self, t ):
cx = self.position.x
cy = self.position.y
for i in xrange(0, self.grid.x+1):
for j in xrange(0, self.grid.y+1):
x,y,z = self.get_original_vertex(i,j)
r = math.sqrt( (i-self.grid.x/2.0) ** 2 + (j-self.grid.y/2.0) ** 2 )
amplitude = 0.1 * self.amplitude * self.amplitude_rate
a = r * math.cos( math.pi/2.0 + t * math.pi * self.twirls * 2 ) * amplitude
dx = math.sin(a) * (y-cy) + math.cos(a) * (x-cx)
dy = math.cos(a) * (y-cy) - math.sin(a) * (x-cx)
self.set_vertex( i,j, (cx+dx, cy+dy,z) )
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Camera Actions
Actions that moves the OpenGL camera.
'''
__docformat__ = 'restructuredtext'
from cocos.director import director
from cocos.euclid import *
from base_actions import *
import math
__all__ = [ 'CameraException', # Camera Exceptions
'Camera3DAction',
'OrbitCamera',
]
class CameraException( Exception ):
pass
class Camera3DAction( IntervalAction ):
def init( self, duration=2):
"""Initialize the Camera Action
:Parameters:
`duration` : int
Number of seconds that the action will last
"""
self.duration = duration
def start( self ):
super(Camera3DAction, self).start()
self.camera_eye_orig = self.target.camera.eye
self.camera_center_orig = self.target.camera.center
self.camera_up_orig = self.target.camera.up_vector
# def stop( self ):
# super(Camera3DAction, self).stop()
# self.target.camera.eye = self.camera_eye_orig
# self.target.camera.center = self.camera_center_orig
# self.target.camera.up_vector = self.camera_up_orig
def __reversed__( self ):
return _ReverseTime( self )
class OrbitCamera( Camera3DAction ):
'''Orbits the camera around the center of the screen using spherical coordinates
'''
def init( self, radius=None, delta_radius=0, angle_z=None, delta_z=0, angle_x=None, delta_x=0, *args, **kw ):
'''Initialize the camera with spherical coordinates
:Parameters:
`radius` : float
Radius of the orbit. Default: current radius
`delta_radius` : float
Delta movement of the radius. Default: 0
`angle_z` : float
The zenith angle of the spherical coordinate in degrees. Default: current
`delta_z` : float
Relative movement of the zenith angle. Default: 0
`angle_x` : float
The azimuth angle of the spherical coordinate in degrees. Default: 0
`delta_x` : float
Relative movement of the azimuth angle. Default: 0
For more information regarding spherical coordinates, read this:
http://en.wikipedia.org/wiki/Spherical_coordinates
'''
super( OrbitCamera, self ).init( *args, **kw )
width, height = director.get_window_size()
self.radius = radius
self.delta_radius = delta_radius
self.angle_x = angle_x
self.rad_delta_x= math.radians( delta_x )
self.angle_z = angle_z
self.rad_delta_z = math.radians( delta_z )
def start( self ):
super(OrbitCamera,self).start()
radius, zenith, azimuth = self.get_spherical_coords()
if self.radius is None:
self.radius = radius
if self.angle_z is None:
self.angle_z= math.degrees(zenith)
if self.angle_x is None:
self.angle_x= math.degrees(azimuth)
self.rad_x = math.radians( self.angle_x )
self.rad_z = math.radians( self.angle_z )
def get_spherical_coords( self ):
'''returns the spherical coordinates from a cartesian coordinates
using this formula:
- http://www.math.montana.edu/frankw/ccp/multiworld/multipleIVP/spherical/body.htm#converting
:rtype: ( radius, zenith, azimuth )
'''
eye = self.target.camera.eye - self.target.camera.center
radius = math.sqrt( pow(eye.x,2) + pow(eye.y,2) + pow(eye.z,2) )
s = math.sqrt( pow(eye.x,2) + pow(eye.y,2) )
if s == 0:
s = 0.000000001
r = radius
if r == 0:
r = 0.000000001
angle_z = math.acos( eye.z / float(r) )
if eye.x < 0:
angle_x = math.pi - math.asin( eye.y / s )
else:
angle_x = math.asin( eye.y / s )
radius = radius / self.target.camera.get_z_eye()
return radius, angle_z, angle_x
def update( self, t ):
r = (self.radius + self.delta_radius * t) * self.target.camera.get_z_eye()
z_angle = self.rad_z + self.rad_delta_z * t
x_angle = self.rad_x + self.rad_delta_x * t
# using spherical coordinates
p = Point3( math.sin(z_angle) * math.cos(x_angle),
math.sin(z_angle) * math.sin(x_angle),
math.cos(z_angle) )
p = p * r
d = p + self.camera_center_orig
self.target.camera.eye = d
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Actions for moving things around based on their velocity and
acceleration.
The simplest usage:
sprite = cocos.sprite.Sprite('ship.png')
sprite.velocity = (100, 100)
sprite.do(Move())
This will move the sprite (100, 100) pixels per second indefinitely.
Typically the sprite would be controlled by the user, so something like::
keys = <standard pyglet keyboard state handler>
class MoveShip(Move):
def step(self, dt):
super(MoveShip, self).step(dt)
self.target.dr = (keys[key.RIGHT] - keys[key.LEFT]) * 360
rotation = math.pi * self.target.rotation / 180.0
rotation_x = math.cos(-rotation)
rotation_y = math.sin(-rotation)
if keys[key.UP]:
self.target.acceleration = (200 * rotation_x, 200 * rotation_y)
ship.do(MoveShip())
'''
__docformat__ = 'restructuredtext'
__all__ = [
'Move', 'WrappedMove', 'BoundedMove', 'Driver',
]
import math
from base_actions import Action
class Move(Action):
"""Move the target based on parameters on the target.
For movement the parameters are::
target.position = (x, y)
target.velocity = (dx, dy)
target.acceleration = (ddx, ddy) = (0, 0)
target.gravity = 0
And rotation::
target.rotation
target.dr
target.ddr
"""
def step(self, dt):
x, y = self.target.position
dx, dy = self.target.velocity
ddx, ddy = getattr(self.target, 'acceleration', (0, 0))
gravity = getattr(self.target, 'gravity', 0)
dx += ddx * dt
dy += (ddy + gravity) * dt
self.target.velocity = (dx, dy)
x += dx * dt
y += dy * dt
self.target.position = (x, y)
dr = getattr(self.target, 'dr', 0)
ddr = getattr(self.target, 'ddr', 0)
if dr or ddr:
dr = self.target.dr = dr + ddr * dt
if dr:
self.target.rotation += dr * dt
class WrappedMove(Move):
"""Move the target but wrap position when it hits certain bounds.
Wrap occurs outside of 0 < x < width and 0 < y < height taking into
account the dimenstions of the target.
"""
def init(self, width, height):
"""Init method.
:Parameters:
`width` : integer
The width to wrap position at.
`height` : integer
The height to wrap position at.
"""
self.width, self.height = width, height
def step(self, dt):
super(WrappedMove, self).step(dt)
x, y = self.target.position
w, h = self.target.width, self.target.height
# XXX assumes center anchor
if x > self.width + w/2:
x -= self.width + w
elif x < 0 - w/2:
x += self.width + w
if y > self.height + h/2:
y -= self.height + h
elif y < 0 - h/2:
y += self.height + h
self.target.position = (x, y)
class BoundedMove(Move):
"""Move the target but limit position when it hits certain bounds.
Position is bounded to 0 < x < width and 0 < y < height taking into
account the dimenstions of the target.
"""
def init(self, width, height):
"""Init method.
:Parameters:
`width` : integer
The width to bound position at.
`height` : integer
The height to bound position at.
"""
self.width, self.height = width, height
def step(self, dt):
super(BoundedMove, self).step(dt)
x, y = self.target.position
w, h = self.target.width, self.target.height
# XXX assumes center anchor
if x > self.width - w/2:
x = self.width - w/2
elif x < w/2:
x = w/2
if y > self.height - h/2:
y = self.height - h/2
elif y < h/2:
y = h/2
self.target.position = (x, y)
class Driver(Action):
"""Drive a `CocosNode` object around like a car in x, y according to
a direction and speed.
Example::
# control the movement of the given sprite
sprite.do(Driver())
...
sprite.rotation = 45
sprite.speed = 100
...
The sprite MAY have these parameters (beyond the standard position
and rotation):
`speed` : float
Speed to move at in pixels per second in the direction of
the target's rotation.
`acceleration` : float
If specified will automatically be added to speed.
Specified in pixels per second per second.
`max_forward_speed` : float (default None)
Limits to apply to speed when updating with acceleration.
`max_reverse_speed` : float (default None)
Limits to apply to speed when updating with acceleration.
"""
def step(self, dt):
accel = getattr(self.target, 'acceleration', 0)
speed = getattr(self.target, 'speed', 0)
max_forward = getattr(self.target, 'max_forward_speed', None)
max_reverse = getattr(self.target, 'max_reverse_speed', None)
if accel:
speed += dt * accel
if max_forward is not None and self.target.speed > max_forward:
speed = max_forward
if max_reverse is not None and self.target.speed < max_reverse:
speed = max_reverse
r = math.radians(self.target.rotation)
s = dt * speed
x, y = self.target.position
self.target.position = (x + math.sin(r) * s, y + math.cos(r) * s)
self.target.speed = speed
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Implementation of QuadMoveBy actions
These actions modifies the x and y coordinates of fixed-size grid of (1,1).
The z-coordinate is not modified.
'''
__docformat__ = 'restructuredtext'
import math
from cocos.director import director
from cocos.euclid import *
from basegrid_actions import *
__all__ = ['QuadMoveBy',
'MoveCornerUp',
'MoveCornerDown',
'CornerSwap',
'Flip',
'FlipX',
'FlipY',
'SkewHorizontal',
'SkewVertical',
]
class QuadMoveBy( Grid3DAction ):
'''QuadMoveBy moves each vertex of the grid. The size of the grid is (1,1)
Vertex positions::
vertex3 --<-- vertex2
| |
v ^
| |
vertex0 -->-- vertex1
The vertices will move from the origin (src parameters) a relative distance (delta parameters) in duration time.
Example::
scene.do( QuadMoveBy( src0, src1, src2, src3,
delta0, delta1, delta2, delta3,
duration) )
'''
def init( self,
src0=(0,0), src1=(-1,-1), src2=(-1,-1), src3=(-1,-1),
delta0=(0,0), delta1=(0,0), delta2=(0,0), delta3=(0,0),
grid=(1,1),
*args, **kw ):
'''Initializes the QuadMoveBy
:Parameters:
`src0` : (int, int)
Initial value for the bottom-left coordinate. Default is (0,0)
`src1` : (int, int)
Initial value for the bottom-right coordinate. Default is (win_size_x,0)
`src2` : (int, int)
Initial value for the upper-right coordinate. Default is (win_size_x, win_size_y)
`src3` : (int, int)
Initial value for the upper-left coordinate. Default is (0, win_size_y)
`delta0` : (int, int)
The bottom-left relative coordinate. Default is (0,0)
`delta1` : (int, int)
The bottom-right relative coordinate. Default is (0,0)
`delta2` : (int, int)
The upper-right relative coordinate. Default is (0,0)
`delta3` : (int, int)
The upper-left relative coordinate. Default is (0,0)
'''
if grid != (1,1):
raise GridException("Invalid grid size.")
super( QuadMoveBy, self).init( grid, *args, **kw )
x,y = director.get_window_size()
if src1 == (-1,-1):
src1 = ( x,0 )
if src2 == (-1,-1):
src2 = (x,y)
if src3 == (-1,-1):
src3 = (0,y)
self.src0 = Point3( src0[0], src0[1], 0 )
self.src1 = Point3( src1[0], src1[1], 0 )
self.src2 = Point3( src2[0], src2[1], 0 )
self.src3 = Point3( src3[0], src3[1], 0)
self.delta0 = Point3( delta0[0], delta0[1], 0)
self.delta1 = Point3( delta1[0], delta1[1], 0)
self.delta2 = Point3( delta2[0], delta2[1], 0)
self.delta3 = Point3( delta3[0], delta3[1], 0)
def update( self, t ):
new_pos0 = self.src0 + self.delta0 * t
new_pos1 = self.src1 + self.delta1 * t
new_pos2 = self.src2 + self.delta2 * t
new_pos3 = self.src3 + self.delta3 * t
self.set_vertex( 0,0, new_pos0 )
self.set_vertex( 1,0, new_pos1 )
self.set_vertex( 1,1, new_pos2 )
self.set_vertex( 0,1, new_pos3 )
class MoveCornerUp( QuadMoveBy ):
'''MoveCornerUp moves the bottom-right corner to the upper-left corner in duration time'''
def __init__(self, *args, **kw):
x,y = director.get_window_size()
super(MoveCornerUp, self).__init__( delta1=(-x,y), *args, **kw )
class MoveCornerDown( QuadMoveBy ):
'''MoveCornerDown moves the upper-left corner to the bottom-right corner in duration time'''
def __init__(self, *args, **kw):
x,y = director.get_window_size()
super(MoveCornerDown, self).__init__( delta3=(x,-y), *args, **kw )
class CornerSwap( QuadMoveBy ):
'''CornerSwap moves the upper-left corner to the bottom-right corner in vice-versa in duration time.
The resulting effect is a reflection + rotation.
'''
def __init__(self, *args, **kw):
x,y = director.get_window_size()
super(CornerSwap, self).__init__( delta1=(-x,y), delta3=(x,-y), *args, **kw )
class Flip( QuadMoveBy ):
'''Flip moves the upper-left corner to the bottom-left corner and vice-versa, and
moves the upper-right corner to the bottom-left corner and vice-versa, flipping the
window upside-down, and right-left.
'''
def __init__(self, *args, **kw):
x,y = director.get_window_size()
super(Flip, self).__init__( delta0=(x,y), delta1=(-x,y), delta2=(-x,-y), delta3=(x,-y), *args, **kw )
class FlipX( QuadMoveBy ):
'''FlipX flips the screen horizontally, moving the left corners to the right, and vice-versa.
'''
def __init__(self, *args, **kw):
x,y = director.get_window_size()
super(FlipX, self).__init__( delta0=(x,0), delta1=(-x,0), delta2=(-x,0), delta3=(x,0), *args, **kw )
class FlipY( QuadMoveBy ):
'''FlipY flips the screen vertically, moving the upper corners to the bottom, and vice-versa.
'''
def __init__(self, *args, **kw):
x,y = director.get_window_size()
super(FlipY, self).__init__( delta0=(0,y), delta1=(0,y), delta2=(0,-y), delta3=(0,-y), *args, **kw )
class SkewHorizontal( QuadMoveBy ):
'''SkewHorizontal skews the screen horizontally. default skew: x/3'''
def __init__(self, delta=None, *args, **kw):
x,y = director.get_window_size()
if delta==None:
delta=x//3
super(SkewHorizontal, self).__init__( delta1=(-delta,0), delta3=(delta,0), *args, **kw )
class SkewVertical( QuadMoveBy ):
'''SkewVertical skews the screen vertically. default skew: y/3'''
def __init__(self, delta=None, *args, **kw):
x,y = director.get_window_size()
if delta==None:
delta=y//3
super(SkewVertical, self).__init__( delta0=(0,delta), delta2=(0,-delta), *args, **kw )
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from base_actions import *
from interval_actions import *
from instant_actions import *
from basegrid_actions import *
from quadmoveby_actions import *
from tiledgrid_actions import *
from grid3d_actions import *
from camera_actions import *
from move_actions import *
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Instant Actions
Instant Actions
===============
Instant actions are immediate actions. They don't have a duration like
the Interval Actions.
'''
__docformat__ = 'restructuredtext'
import copy
from base_actions import *
__all__ = [
'Place', # placement action
'CallFunc','CallFuncS', # Calls a function
'Hide','Show','ToggleVisibility', # Visibility actions
]
class Place( InstantAction ):
"""Place the `CocosNode` object in the position x,y.
Example::
action = Place( (320,240) )
sprite.do( action )
"""
def init(self, position):
"""Init method.
:Parameters:
`position` : (x,y)
Coordinates where the sprite will be placed
"""
self.position = position
def start(self):
self.target.position = self.position
class Hide( InstantAction ):
"""Hides the `CocosNode` object. To show it again call the `Show` () action
Example::
action = Hide()
sprite.do( action )
"""
def start(self):
self.target.visible = False
def __reversed__(self):
return Show()
class Show( InstantAction ):
"""Shows the `CocosNode` object. To hide it call the `Hide` () action
Example::
action = Show()
sprite.do( action )
"""
def start(self):
self.target.visible = True
def __reversed__(self):
return Hide()
class ToggleVisibility( InstantAction ):
"""Toggles the visible attribute of a `CocosNode` object
Example::
action = ToggleVisibility()
sprite.do( action )
"""
def start(self):
self.target.visible = not self.target.visible
def __reversed__(self):
return self
class CallFunc(InstantAction):
"""An action that will call a function.
Example::
def my_func():
print "hello baby"
action = CallFunc( my_func )
sprite.do( action )
"""
def init(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def start(self):
self.func(*self.args, **self.kwargs)
def __deepcopy__(self, memo):
return copy.copy( self )
def __reversed__(self):
return self
class CallFuncS(CallFunc):
"""An action that will call a funtion with the target as the first argument
Example::
def my_func( sprite ):
print "hello baby"
action = CallFuncS( my_func )
sprite.do( action )
"""
def start(self):
self.func( self.target, *self.args, **self.kwargs)
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Pre-defined Particle Systems'''
__all__ = ['Fireworks', 'Spiral', 'Meteor', 'Sun', 'Fire', 'Galaxy', 'Flower', 'Explosion', 'Smoke']
from particle import ParticleSystem, Color
from euclid import Point2
class Fireworks( ParticleSystem ):
# total particles
total_particles = 3000
# duration
duration = -1
# gravity
gravity = Point2(0,-90)
# angle
angle = 90
angle_var = 20
# radial
radial_accel = 0
radial_accel_var = 0
# speed of particles
speed = 180
speed_var = 50
# emitter variable position
pos_var = Point2(0,0)
# life of particles
life = 3.5
life_var = 1
# emits per frame
emission_rate = total_particles / life
# color of particles
start_color = Color(0.5,0.5,0.5,1.0)
start_color_var = Color(0.5, 0.5, 0.5, 1.0)
end_color = Color(0.1,0.1,0.1,0.2)
end_color_var = Color(0.1,0.1,0.1,0.2)
# size, in pixels
size = 8.0
size_var = 2.0
# blend additive
blend_additive = False
# color modulate
color_modulate = True
class Explosion( ParticleSystem ):
# total particle
total_particles = 700
# duration
duration = 0.1
# gravity
gravity = Point2(0,-90)
# angle
angle = 90.0
angle_var = 360.0
# radial
radial_accel = 0
radial_accel_var = 0
# speed of particles
speed = 70.0
speed_var = 40.0
# emitter variable position
pos_var = Point2(0,0)
# life of particles
life = 5.0
life_var = 2.0
# emits per frame
emission_rate = total_particles / duration
# color of particles
start_color = Color(0.7, 0.2, 0.1, 1.0)
start_color_var = Color(0.5, 0.5, 0.5, 0.0)
end_color = Color(0.5, 0.5, 0.5, 0.0)
end_color_var = Color(0.5, 0.5, 0.5, 0.0)
# size, in pixels
size = 15.0
size_var = 10.0
# blend additive
blend_additive = False
# color modulate
color_modulate = True
class Fire( ParticleSystem ):
# total particles
total_particles = 250
# duration
duration = -1
# gravity
gravity = Point2(0,0)
# angle
angle = 90.0
angle_var = 10.0
# radial
radial_accel = 0
radial_accel_var = 0
# speed of particles
speed = 60.0
speed_var = 20.0
# emitter variable position
pos_var = Point2(40, 20)
# life of particles
life = 3.0
life_var = 0.25
# emits per frame
emission_rate = total_particles / life
# color of particles
start_color = Color(0.76, 0.25, 0.12, 1.0)
start_color_var = Color(0.0, 0.0, 0.0, 0.0)
end_color = Color(0.0, 0.0, 0.0, 1.0)
end_color_var = Color(0.0, 0.0, 0.0, 0.0)
# size, in pixels
size = 100.0
size_var = 10.0
# blend additive
blend_additive = True
# color modulate
color_modulate = True
class Flower( ParticleSystem ):
# total particles
total_particles = 500
# duration
duration = -1
# gravity
gravity = Point2( 0, 0)
# angle
angle = 90.0
angle_var = 360.0
# speed of particles
speed = 80.0
speed_var = 10.0
# radial
radial_accel = -60
radial_accel_var = 0
# tangential
tangential_accel = 15.0
tangential_accel_var = 0.0
# emitter variable position
pos_var = Point2(0,0)
# life of particles
life = 4.0
life_var = 1.0
# emits per frame
emission_rate = total_particles / life
# color of particles
start_color = Color(0.5, 0.5, 0.5, 1.0)
start_color_var = Color(0.5, 0.5, 0.5, 0.0)
end_color = Color(0.0, 0.0, 0.0, 1.0)
end_color_var = Color(0.0, 0.0, 0.0, 0.0)
# size, in pixels
size = 30.0
size_var = 0.0
# blend additive
blend_additive = True
# color modulate
color_modulate = True
class Sun( ParticleSystem ):
# total particles
total_particles = 350
# duration
duration = -1
# gravity
gravity = Point2(0,0)
# angle
angle = 90.0
angle_var = 360.0
# speed of particles
speed = 20.0
speed_var = 5.0
# radial
radial_accel = 0
radial_accel_var = 0
# tangential
tangential_accel = 0.0
tangential_accel_var = 0.0
# emitter variable position
pos_var = Point2(0, 0)
# life of particles
life = 1.0
life_var = 0.5
# emits per frame
emission_rate = total_particles / life
# color of particles
start_color = Color(0.75, 0.25, 0.12, 1.0)
start_color_var = Color(0.0, 0.0, 0.0, 0.0)
end_color = Color(0.0, 0.0, 0.0, 0.0)
end_color_var = Color(0.0, 0.0, 0.0, 0.0)
# size, in pixels
size = 40.0
size_var = 00.0
# blend additive
blend_additive = True
# color modulate
color_modulate = True
class Spiral( ParticleSystem ):
# total paticles
total_particles = 500
# duration
duration = -1
# gravity
gravity = Point2(0,0)
# angle
angle = 90.0
angle_var = 0.0
# speed of particles
speed = 150.0
speed_var = 0.0
# radial
radial_accel = -380
radial_accel_var = 0
# tangential
tangential_accel = 45.0
tangential_accel_var = 0.0
# emitter variable position
pos_var = Point2(0,0)
# life of particles
life = 12.0
life_var = 0.0
# emits per frame
emission_rate = total_particles / life
# color of particles
start_color = Color(0.5, 0.5, 0.5, 1.0)
start_color_var = Color(0.5, 0.5, 0.5, 0.0)
end_color = Color(0.5, 0.5, 0.5, 1.0)
end_color_var = Color(0.5, 0.5, 0.5, 0.0)
# size, in pixels
size = 20.0
size_var = 10.0
# blend additive
blend_additive = True
# color modulate
color_modulate = True
class Meteor( ParticleSystem ):
# total particles
total_particles = 150
# duration
duration = -1
# gravity
gravity = Point2(-200,100)
# angle
angle = 90.0
angle_var = 360.0
# speed of particles
speed = 15.0
speed_var = 5.0
# radial
radial_accel = 0
radial_accel_var = 0
# tangential
tangential_accel = 0.0
tangential_accel_var = 0.0
# emitter variable position
pos_var = Point2(0,0)
# life of particles
life = 2.0
life_var = 1.0
# size, in pixels
size = 60.0
size_var = 10.0
# emits per frame
emission_rate = total_particles / life
# color of particles
start_color = Color(0.2, 0.7, 0.7, 1.0)
start_color_var = Color(0.0, 0.0, 0.0, 0.2)
end_color = Color(0.0, 0.0, 0.0, 1.0)
end_color_var = Color(0.0, 0.0, 0.0, 0.0)
# blend additive
blend_additive = True
# color modulate
color_modulate = True
class Galaxy( ParticleSystem ):
# total particles
total_particles = 200
# duration
duration = -1
# gravity
gravity = Point2(0,0)
# angle
angle = 90.0
angle_var = 360.0
# speed of particles
speed = 60.0
speed_var = 10.0
# radial
radial_accel = -80.0
radial_accel_var = 0
# tangential
tangential_accel = 80.0
tangential_accel_var = 0.0
# emitter variable position
pos_var = Point2(0,0)
# life of particles
life = 4.0
life_var = 1.0
# size, in pixels
size = 37.0
size_var = 10.0
# emits per frame
emission_rate = total_particles / life
# color of particles
start_color = Color(0.12, 0.25, 0.76, 1.0)
start_color_var = Color(0.0, 0.0, 0.0, 0.0)
end_color = Color(0.0, 0.0, 0.0, 0.0)
end_color_var = Color(0.0, 0.0, 0.0, 0.0)
# blend additive
blend_additive = True
# color modulate
color_modulate = True
class Smoke( ParticleSystem ):
# total particles
total_particles = 80
# duration
duration = -1
# gravity
gravity = Point2(0,0)
# angle
angle = 90.0
angle_var = 10.0
# speed of particles
speed = 25.0
speed_var = 10.0
# radial
radial_accel = 5
radial_accel_var = 0
# tangential
tangential_accel = 0.0
tangential_accel_var = 0.0
# emitter variable position
pos_var = Point2(0.1,0)
# life of particles
life = 4.0
life_var = 1.0
# size, in pixels
size = 40.0
size_var = 10.0
# emits per frame
emission_rate = total_particles / life
start_color = Color(0.5,0.5,0.5,0.1)
start_color_var = Color(0,0,0,0.1)
end_color = Color(0.5,0.5,0.5,0.1)
end_color_var = Color(0,0,0,0.1)
# blend additive
blend_additive = True
# color modulate
color_modulate = False
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Particle system engine'''
__docformat__ = 'restructuredtext'
import random
import pyglet
from pyglet.gl import *
import math
import copy
import numpy
import ctypes
from cocosnode import CocosNode
from euclid import Point2
class ExceptionNoEmptyParticle(Exception):
"""particle system have no room for another particle"""
pass
rand = lambda: random.random() * 2 - 1
# PointerToNumpy by Gary Herron
# from pyglet's user list
def PointerToNumpy(a, ptype=ctypes.c_float):
a = numpy.ascontiguousarray(a) # Probably a NO-OP, but perhaps not
return a.ctypes.data_as(ctypes.POINTER(ptype)) # Ugly and undocumented!
class Color( object ):
def __init__( self, r,g,b,a ):
self.r = r
self.g = g
self.b = b
self.a = a
def to_array(self):
return self.r, self.g, self.b, self.a
class ParticleSystem( CocosNode ):
# type of particle
POSITION_FREE, POSITION_GROUPED = range(2)
#: is the particle system active ?
active = True
#: duration in seconds of the system. -1 is infinity
duration = 0
#: time elapsed since the start of the system (in seconds)
elapsed = 0
#: Gravity of the particles
gravity = Point2(0.0, 0.0)
#: position is from "superclass" CocosNode
#: Position variance
pos_var = Point2(0.0, 0.0)
#: The angle (direction) of the particles measured in degrees
angle = 0.0
#: Angle variance measured in degrees;
angle_var = 0.0
#: The speed the particles will have.
speed = 0.0
#: The speed variance
speed_var = 0.0
#: Tangential acceleration
tangential_accel = 0.0
#: Tangential acceleration variance
tangential_accel_var = 0.0
#: Radial acceleration
radial_accel = 0.0
#: Radial acceleration variance
radial_accel_var = 0.0
#: Size of the particles
size = 0.0
#: Size variance
size_var = 0.0
#: How many seconds will the particle live
life = 0
#: Life variance
life_var = 0
#: Start color of the particles
start_color = Color(0.0,0.0,0.0,0.0)
#: Start color variance
start_color_var = Color(0.0,0.0,0.0,0.0)
#: End color of the particles
end_color = Color(0.0,0.0,0.0,0.0)
#: End color variance
end_color_var = Color(0.0,0.0,0.0,0.0)
#: Maximum particles
total_particles = 0
#:texture of the particles
texture = pyglet.resource.image('fire.png').texture
#:blend additive
blend_additive = False
#:color modulate
color_modulate = True
# position type
position_type = POSITION_GROUPED
def __init__(self):
super(ParticleSystem,self).__init__()
# particles
# position x 2
self.particle_pos = numpy.zeros( (self.total_particles, 2), numpy.float32 )
# direction x 2
self.particle_dir = numpy.zeros( (self.total_particles, 2), numpy.float32 )
# rad accel x 1
self.particle_rad = numpy.zeros( (self.total_particles, 1), numpy.float32 )
# tan accel x 1
self.particle_tan = numpy.zeros( (self.total_particles, 1), numpy.float32 )
# gravity x 2
self.particle_grav = numpy.zeros( (self.total_particles, 2), numpy.float32 )
# colors x 4
self.particle_color = numpy.zeros( (self.total_particles, 4), numpy.float32 )
# delta colors x 4
self.particle_delta_color = numpy.zeros( (self.total_particles, 4), numpy.float32 )
# life x 1
self.particle_life = numpy.zeros( (self.total_particles, 1), numpy.float32 )
self.particle_life.fill(-1.0)
# size x 1
self.particle_size = numpy.zeros( (self.total_particles, 1), numpy.float32 )
# start position
self.start_pos = numpy.zeros( (self.total_particles, 2), numpy.float32 )
#: How many particles can be emitted per second
self.emit_counter = 0
#: Count of particles
self.particle_count = 0
#: auto remove when particle finishes
self.auto_remove_on_finish = False
self.schedule( self.step )
def on_enter( self ):
super( ParticleSystem, self).on_enter()
#self.add_particle()
def draw( self ):
glPushMatrix()
self.transform()
glPointSize( self.size )
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, self.texture.id )
glEnable(GL_POINT_SPRITE)
glTexEnvi( GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE )
glEnableClientState(GL_VERTEX_ARRAY)
vertex_ptr = PointerToNumpy( self.particle_pos )
glVertexPointer(2,GL_FLOAT,0,vertex_ptr);
glEnableClientState(GL_COLOR_ARRAY)
color_ptr = PointerToNumpy( self.particle_color)
glColorPointer(4,GL_FLOAT,0,color_ptr);
glPushAttrib(GL_COLOR_BUFFER_BIT)
glEnable(GL_BLEND)
if self.blend_additive:
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
else:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
# mode = GLint()
# glTexEnviv( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, mode )
#
# if self.color_modulate:
# glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE )
# else:
# glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE )
glDrawArrays(GL_POINTS, 0, self.total_particles);
# un -blend
glPopAttrib()
# # restore env mode
# glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, mode)
# disable states
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glDisable(GL_POINT_SPRITE);
glDisable(GL_TEXTURE_2D);
glPopMatrix()
def step( self, delta ):
# update particle count
self.particle_count = numpy.sum( self.particle_life >= 0 )
if self.active:
rate = 1.0 / self.emission_rate
self.emit_counter += delta
# if random.random() < 0.01:
# delta += 0.5
while self.particle_count < self.total_particles and self.emit_counter > rate:
self.add_particle()
self.emit_counter -= rate
self.elapsed += delta
if self.duration != -1 and self.duration < self.elapsed:
self.stop_system()
self.update_particles( delta )
if (not self.active and
self.particle_count == 0 and self.auto_remove_on_finish == True):
self.unschedule( self.step )
self.parent.remove( self )
def add_particle( self ):
"""
Code calling add_particle must be either:
be sure there is room for the particle
or
be prepared to catch the exception ExceptionNoEmptyParticle
It is acceptable to try: ... except...: pass
"""
self.init_particle()
self.particle_count += 1
def stop_system( self ):
self.active = False
self.elapsed= self.duration
self.emit_counter = 0
def reset_system( self ):
self.elapsed= self.duration
self.emit_counter = 0
def update_particles( self, delta ):
# radial: posx + posy
norm = numpy.sqrt( self.particle_pos[:,0] ** 2 + self.particle_pos[:,1] ** 2 )
# XXX prevent div by 0
norm = numpy.select( [norm==0], [0.0000001], default=norm )
posx = self.particle_pos[:,0] / norm
posy = self.particle_pos[:,1] / norm
radial = numpy.array( [posx, posy] )
tangential = numpy.array( [-posy, posx] )
# update dir
radial = numpy.swapaxes(radial,0,1)
radial *= self.particle_rad
tangential = numpy.swapaxes(tangential,0,1)
tangential *= self.particle_tan
self.particle_dir += (tangential + radial + self.particle_grav) * delta
# update pos with updated dir
self.particle_pos += self.particle_dir * delta
# life
self.particle_life -= delta
# position: free or grouped
if self.position_type == self.POSITION_FREE:
tuple = numpy.array( [self.x, self.y] )
tmp = tuple - self.start_pos
self.particle_pos -= tmp
# color
self.particle_color += self.particle_delta_color * delta
# if life < 0, set alpha in 0
self.particle_color[:,3] = numpy.select( [self.particle_life[:,0] < 0], [0], default=self.particle_color[:,3] )
# print self.particles[0]
# print self.pas[0,0:4]
def init_particle( self ):
# position
# p=self.particles[idx]
a = self.particle_life < 0
idxs = a.nonzero()
idx = -1
if len(idxs[0]) > 0:
idx = idxs[0][0]
else:
raise ExceptionNoEmptyParticle()
# position
self.particle_pos[idx][0] = self.pos_var.x * rand()
self.particle_pos[idx][1] = self.pos_var.y * rand()
# start position
self.start_pos[idx][0] = self.x
self.start_pos[idx][1] = self.y
a = math.radians( self.angle + self.angle_var * rand() )
v = Point2( math.cos( a ), math.sin( a ) )
s = self.speed + self.speed_var * rand()
dir = v * s
# direction
self.particle_dir[idx][0] = dir.x
self.particle_dir[idx][1] = dir.y
# radial accel
self.particle_rad[idx] = self.radial_accel + self.radial_accel_var * rand()
# tangential accel
self.particle_tan[idx] = self.tangential_accel + self.tangential_accel_var * rand()
# life
life = self.particle_life[idx] = self.life + self.life_var * rand()
# Color
# start
sr = self.start_color.r + self.start_color_var.r * rand()
sg = self.start_color.g + self.start_color_var.g * rand()
sb = self.start_color.b + self.start_color_var.b * rand()
sa = self.start_color.a + self.start_color_var.a * rand()
self.particle_color[idx][0] = sr
self.particle_color[idx][1] = sg
self.particle_color[idx][2] = sb
self.particle_color[idx][3] = sa
# end
er = self.end_color.r + self.end_color_var.r * rand()
eg = self.end_color.g + self.end_color_var.g * rand()
eb = self.end_color.b + self.end_color_var.b * rand()
ea = self.end_color.a + self.end_color_var.a * rand()
delta_color_r = (er - sr) / life
delta_color_g = (eg - sg) / life
delta_color_b = (eb - sb) / life
delta_color_a = (ea - sa) / life
self.particle_delta_color[idx][0] = delta_color_r
self.particle_delta_color[idx][1] = delta_color_g
self.particle_delta_color[idx][2] = delta_color_b
self.particle_delta_color[idx][3] = delta_color_a
# size
self.particle_size[idx] = self.size + self.size_var * rand()
# gravity
self.particle_grav[idx][0] = self.gravity.x
self.particle_grav[idx][1] = self.gravity.y
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""
CocosNode: the basic element of cocos2d
"""
__docformat__ = 'restructuredtext'
import bisect, copy
import pyglet
from pyglet.gl import *
from director import director
from camera import Camera
import euclid
import math
import weakref
__all__ = ['CocosNode']
class CocosNode(object):
"""
Cocosnode is the main element. Anything thats gets drawn or contains things that get drawn is a cocosnode.
The most popular cocosnodes are scenes, layers and sprites.
The main features of a cocosnode are:
- They can contain other cocos nodes (add, get, remove, etc)
- They can schedule periodic callback (schedule, schedule_interval, etc)
- They can execute actions (do, pause, stop, etc)
Some cocosnodes provide extra functionality for them or their children.
Subclassing a cocosnode usually means (one/all) of:
- overriding __init__ to initialize resources and schedule calbacks
- create callbacks to handle the advancement of time
- overriding draw to render the node
"""
def __init__(self):
# composition stuff
#: list of children. each item is (int, child-reference) where int is the z-order
self.children = []
#: dictionary that maps children names with children references
self.children_names = {}
self._parent = None
# drawing stuff
#: x-position of the object relative to its parent's children_anchor_x value.
#: Default: 0
self._x = 0
#: y-position of the object relative to its parent's children_anchor_y value.
#: Default: 0
self._y = 0
#: a float, alters the scale of this node and its children.
#: Default: 1.0
self._scale = 1.0
#: a float, in degrees, alters the rotation of this node and its children.
#: Default: 0.0
self._rotation = 0.0
#: eye, center and up vector for the `Camera`.
#: gluLookAt() is used with these values.
#: Default: FOV 60, center of the screen.
#: IMPORTANT: The camera can perform exactly the same
#: transformation as ``scale``, ``rotation`` and the
#: ``x``, ``y`` attributes (with the exception that the
#: camera can modify also the z-coordinate)
#: In fact, they all transform the same matrix, so
#: use either the camera or the other attributes, but not both
#: since the camera will be overridden by the transformations done
#: by the other attributes.
#: You can change the camera manually or by using the `Camera3DAction`
#: action.
self.camera = Camera()
#: offset from (x,0) from where rotation and scale will be applied.
#: Default: 0
self.transform_anchor_x = 0
#: offset from (0,y) from where rotation and scale will be applied.
#: Default: 0
self.transform_anchor_y = 0
#: whether of not the object is visible.
#: Default: True
self.visible = True
#: the grid object for the grid actions.
#: This can be a `Grid3D` or a `TiledGrid3D` object depending
#: on the action.
self.grid = None
# actions stuff
#: list of `Action` objects that are running
self.actions = []
#: list of `Action` objects to be removed
self.to_remove = []
#: whether or not the next frame will be skipped
self.skip_frame = False
# schedule stuff
self.scheduled = False # deprecated, soon to be removed
self.scheduled_calls = [] #: list of scheduled callbacks
self.scheduled_interval_calls = [] #: list of scheduled interval callbacks
self.is_running = False #: whether of not the object is running
# matrix stuff
self.is_transform_dirty = False
self.transform_matrix = euclid.Matrix3().identity()
self.is_inverse_transform_dirty = False
self.inverse_transform_matrix = euclid.Matrix3().identity()
def make_property(attr):
def set_attr():
def inner(self, value):
setattr(self, "transform_"+attr,value)
return inner
def get_attr():
def inner(self):
return getattr(self,"transform_"+attr)
return inner
return property(
get_attr(),
set_attr(),
doc="""a property to get fast access to [transform_|children_]
:type: (int,int)
"""+attr )
#: Anchor point of the object.
#: Children will be added at this point
#: and transformations like scaling and rotation will use this point
#: as the center
anchor = make_property("anchor")
#: Anchor x value for transformations and adding children
anchor_x = make_property("anchor_x")
#: Anchor y value for transformations and adding children
anchor_y = make_property("anchor_y")
def make_property(attr):
def set_attr():
def inner(self, value):
setattr(self, attr+"_x",value[0])
setattr(self, attr+"_y",value[1])
return inner
def get_attr(self):
return getattr(self,attr+"_x"), getattr(self,attr+"_y")
return property(
get_attr,
set_attr(),
doc='''a property to get fast access to "+attr+"_[x|y]
:type: (int,int)
''')
#: Transformation anchor point.
#: Transformations like scaling and rotation
#: will use this point as it's center
transform_anchor = make_property("transform_anchor")
del make_property
def schedule_interval(self, callback, interval, *args, **kwargs):
"""
Schedule a function to be called every `interval` seconds.
Specifying an interval of 0 prevents the function from being
called again (see `schedule` to call a function as often as possible).
The callback function prototype is the same as for `schedule`.
:Parameters:
`callback` : function
The function to call when the timer lapses.
`interval` : float
The number of seconds to wait between each call.
This function is a wrapper to pyglet.clock.schedule_interval.
It has the additional benefit that all calllbacks are paused and
resumed when the node leaves or enters a scene.
You should not have to schedule things using pyglet by yourself.
"""
if self.is_running:
pyglet.clock.schedule_interval(callback, interval, *args, **kwargs)
self.scheduled_interval_calls.append(
(callback, interval, args, kwargs)
)
def schedule(self, callback, *args, **kwargs):
"""
Schedule a function to be called every frame.
The function should have a prototype that includes ``dt`` as the
first argument, which gives the elapsed time, in seconds, since the
last clock tick. Any additional arguments given to this function
are passed on to the callback::
def callback(dt, *args, **kwargs):
pass
:Parameters:
`callback` : function
The function to call each frame.
This function is a wrapper to pyglet.clock.schedule.
It has the additional benefit that all calllbacks are paused and
resumed when the node leaves or enters a scene.
You should not have to schedule things using pyglet by yourself.
"""
if self.is_running:
pyglet.clock.schedule(callback, *args, **kwargs)
self.scheduled_calls.append(
(callback, args, kwargs)
)
def unschedule(self, callback):
"""
Remove a function from the schedule.
If the function appears in the schedule more than once, all occurances
are removed. If the function was not scheduled, no error is raised.
:Parameters:
`callback` : function
The function to remove from the schedule.
This function is a wrapper to pyglet.clock.unschedule.
It has the additional benefit that all calllbacks are paused and
resumed when the node leaves or enters a scene.
You should not unschedule things using pyglet that where scheduled
by node.schedule/node.schedule_interface.
"""
total_len = len(self.scheduled_calls + self.scheduled_interval_calls)
self.scheduled_calls = [
c for c in self.scheduled_calls if c[0] != callback
]
self.scheduled_interval_calls = [
c for c in self.scheduled_interval_calls if c[0] != callback
]
if self.is_running:
pyglet.clock.unschedule( callback )
def resume_scheduler(self):
"""
Time will continue/start passing for this node and callbacks
will be called, worker actions will be called
"""
for c, i, a, k in self.scheduled_interval_calls:
pyglet.clock.schedule_interval(c, i, *a, **k)
for c, a, k in self.scheduled_calls:
pyglet.clock.schedule(c, *a, **k)
def pause_scheduler(self):
"""
Time will stop passing for this node: scheduled callbacks will
not be called, worker actions will not be called
"""
for f in set(
[ x[0] for x in self.scheduled_interval_calls ] +
[ x[0] for x in self.scheduled_calls ]
):
pyglet.clock.unschedule(f)
for arg in self.scheduled_calls:
pyglet.clock.unschedule(arg[0])
def _get_parent(self):
if self._parent is None: return None
else: return self._parent()
def _set_parent(self, parent):
if parent is None: self._parent = None
else: self._parent = weakref.ref(parent)
parent = property(_get_parent, _set_parent, doc='''The parent of this object.
:type: object
''')
def get_ancestor(self, klass):
"""
Walks the nodes tree upwards until it finds a node of the class `klass`
or returns None
:rtype: `CocosNode` or None
"""
if isinstance(self, klass):
return self
parent = self.parent
if parent:
return parent.get_ancestor( klass )
#
# Transform properties
#
def _get_x(self):
return self._x
def _set_x(self, x):
self._x = x
self.is_transform_dirty = True
self.is_inverse_transform_dirty = True
x = property(_get_x, lambda self,x:self._set_x(x), doc="The x coordinate of the object")
def _get_y(self):
return self._y
def _set_y(self, y):
self._y = y
self.is_transform_dirty = True
self.is_inverse_transform_dirty = True
y = property(_get_y, lambda self,y:self._set_y(y), doc="The y coordinate of the object")
def _get_position(self):
return (self._x, self._y)
def _set_position(self, (x,y)):
self.x, self.y = x,y
self.is_transform_dirty = True
self.is_inverse_transform_dirty = True
position = property(_get_position, lambda self,p:self._set_position(p),
doc='''The (x, y) coordinates of the object.
:type: (int, int)
''')
def _get_scale( self ):
return self._scale
def _set_scale( self, s ):
self._scale = s
self.is_transform_dirty = True
self.is_inverse_transform_dirty = True
scale = property( _get_scale, lambda self, scale: self._set_scale(scale))
def _get_rotation( self ):
return self._rotation
def _set_rotation( self, a ):
self._rotation = a
self.is_transform_dirty = True
self.is_inverse_transform_dirty = True
rotation = property( _get_rotation, lambda self, angle: self._set_rotation(angle))
def add(self, child, z=0, name=None ):
"""Adds a child to the container
:Parameters:
`child` : CocosNode
object to be added
`z` : float
the z index of self
`name` : str
Name of the child
:rtype: `CocosNode` instance
:return: self
"""
# child must be a subclass of supported_classes
#if not isinstance( child, self.supported_classes ):
# raise TypeError("%s is not instance of: %s" % (type(child), self.supported_classes) )
if name:
if name in self.children_names:
raise Exception("Name already exists: %s" % name )
self.children_names[ name ] = child
child.parent = self
elem = z, child
bisect.insort( self.children, elem )
if self.is_running:
child.on_enter()
return self
def kill(self):
'''Remove this object from its parent, and thus most likely from
everything.
'''
self.parent.remove(self)
def remove( self, obj ):
"""Removes a child from the container given its name or object
If the node was added with name, it is better to remove by name, else
the name will be unavailable for further adds ( and will raise Exception
if add with this same name is attempted)
:Parameters:
`obj` : string or object
name of the reference to be removed
or object to be removed
"""
if isinstance(obj, str):
if obj in self.children_names:
child = self.children_names.pop( obj )
self._remove( child )
else:
raise Exception("Child not found: %s" % obj )
else:
self._remove(obj)
def _remove( self, child ):
l_old = len(self.children)
self.children = [ (z,c) for (z,c) in self.children if c != child ]
if l_old == len(self.children):
raise Exception("Child not found: %s" % str(child) )
if self.is_running:
child.on_exit()
def get_children(self):
"""Return a list with the node's childs
:rtype: list of CocosNode
:return: childs of this node
"""
return [ c for (z, c) in self.children ]
def __contains__(self, child):
return child in self.get_children()
def get( self, name ):
"""Gets a child from the container given its name
:Parameters:
`name` : string
name of the reference to be get
:rtype: CocosNode
:return: the child named 'name'. Will raise Exception if not present
Warning: if a node is added with name, then removed not by name, the name
cannot be recycled: attempting to add other node with this name will
produce an Exception.
"""
if name in self.children_names:
return self.children_names[ name ]
else:
raise Exception("Child not found: %s" % name )
def on_enter( self ):
"""
Called every time just before the node enters the stage.
Schedulled calls and worker actions continues to perform
Good point to do .push_handlers if you have custom ones
Rule: a handler pushed there is near certain to require a .pop_handlers
in the .on_exit method (else it will be called even after removed from
the active scene, or, if going on stage again will be called multiple
times for each event ocurrence)
"""
self.is_running = True
# start actions
self.resume()
# resume scheduler
self.resume_scheduler()
# propagate
for c in self.get_children():
c.on_enter()
def on_exit( self ):
"""
Called every time just before the node leaves the stage
Schedulled calls and worker actions are suspended, that is, will not
be called until an on_enter event happens.
Most of the time you will want to .pop_handlers for all explicit
.push_handlers found in on_enter
Consider to release here openGL resources created by this node, like
compiled vertex lists
"""
self.is_running = False
# pause actions
self.pause()
# pause callbacks
self.pause_scheduler()
# propagate
for c in self.get_children():
c.on_exit()
def transform( self ):
"""
Apply ModelView transformations
you will most likely want to wrap calls to this function with
glPushMatrix/glPopMatrix
"""
x,y = director.get_window_size()
if not(self.grid and self.grid.active):
# only apply the camera if the grid is not active
# otherwise, the camera will be applied inside the grid
self.camera.locate()
glTranslatef( self.position[0], self.position[1], 0 )
glTranslatef( self.transform_anchor_x, self.transform_anchor_y, 0 )
if self.rotation != 0.0:
glRotatef( -self._rotation, 0, 0, 1)
if self.scale != 1.0:
glScalef( self._scale, self._scale, 1)
if self.transform_anchor != (0,0):
glTranslatef(
- self.transform_anchor_x,
- self.transform_anchor_y,
0 )
def walk(self, callback, collect=None):
"""
Executes callback on all the subtree starting at self.
returns a list of all return values that are not none
:Parameters:
`callback` : function
callable, takes a cocosnode as argument
`collect` : list
list of visited nodes
:rtype: list
:return: the list of not-none return values
"""
if collect is None:
collect = []
r = callback(self)
if r is not None:
collect.append( r )
for node in self.get_children():
node.walk(callback, collect)
return collect
def visit(self):
'''
This function *visits* it's children in a recursive
way.
It will first *visit* the children that
that have a z-order value less than 0.
Then it will call the `draw` method to
draw itself.
And finally it will *visit* the rest of the
children (the ones with a z-value bigger
or equal than 0)
Before *visiting* any children it will call
the `transform` method to apply any possible
transformation.
'''
if not self.visible:
return
position = 0
if self.grid and self.grid.active:
self.grid.before_draw()
# we visit all nodes that should be drawn before ourselves
if self.children and self.children[0][0] < 0:
glPushMatrix()
self.transform()
for z,c in self.children:
if z >= 0: break
position += 1
c.visit()
glPopMatrix()
# we draw ourselves
self.draw()
# we visit all the remaining nodes, that are over ourselves
if position < len(self.children):
glPushMatrix()
self.transform()
for z,c in self.children[position:]:
c.visit()
glPopMatrix()
if self.grid and self.grid.active:
self.grid.after_draw( self.camera )
def draw(self, *args, **kwargs):
"""
This is the function you will have to override if you want your
subclassed to draw something on screen.
You *must* respect the position, scale, rotation and anchor attributes.
If you want OpenGL to do the scaling for you, you can::
def draw(self):
glPushMatrix()
self.transform()
# ... draw ..
glPopMatrix()
"""
pass
def do( self, action, target=None ):
'''Executes an *action*.
When the action finished, it will be removed from the node's actions
container.
:Parameters:
`action` : an `Action` instance
Action that will be executed.
:rtype: `Action` instance
:return: A clone of *action*
to remove an action you must use the .do return value to
call .remove_action
'''
a = copy.deepcopy( action )
if target is None:
a.target = self
else:
a.target = target
a.start()
self.actions.append( a )
if not self.scheduled:
if self.is_running:
self.scheduled = True
pyglet.clock.schedule( self._step )
return a
def remove_action(self, action):
"""Removes an action from the node actions container, potentially calling action.stop()
If action was running, action.stop is called
Mandatory interfase to remove actions in the node actions container.
When skipping this there is the posibility to double call the action.stop
:Parameters:
`action` : Action
Action to be removed
Must be the return value for a .do(...) call
"""
assert action in self.actions
if not action.scheduled_to_remove:
action.scheduled_to_remove = True
action.stop()
action.target = None
self.to_remove.append( action )
def pause(self):
"""
Suspends the execution of actions.
"""
if not self.scheduled:
return
self.scheduled = False
pyglet.clock.unschedule( self._step )
def resume(self):
"""
Resumes the execution of actions.
"""
if self.scheduled:
return
self.scheduled = True
pyglet.clock.schedule( self._step )
self.skip_frame = True
def stop(self):
"""
Removes all actions from the running action list
For each action running the stop method will be called,
and the action will be retired from the actions container.
"""
for action in self.actions:
self.remove_action(action)
def are_actions_running(self):
"""
Determine whether any actions are running.
"""
return bool(set(self.actions) - set(self.to_remove))
def _step(self, dt):
"""pumps all the actions in the node actions container
The actions scheduled to be removed are removed
Then an action.step() is called for each action in the
node actions container, and if the action doenst need any more step
calls will be schedulled to remove. When schedulled to remove,
the stop method for the action is called.
:Parameters:
`dt` : delta_time
The time that elapsed since that last time this functions was called.
"""
for x in self.to_remove:
if x in self.actions:
self.actions.remove( x )
self.to_remove = []
if self.skip_frame:
self.skip_frame = False
return
if len( self.actions ) == 0:
self.scheduled = False
pyglet.clock.unschedule( self._step )
for action in self.actions:
if not action.scheduled_to_remove:
action.step(dt)
if action.done():
self.remove_action( action )
# world to local / local to world methods
def get_local_transform( self ):
'''returns an euclid.Matrix3 with the local transformation matrix
:rtype: euclid.Matrix3
'''
if self.is_transform_dirty:
matrix = euclid.Matrix3().identity()
matrix.translate(self._x, self._y)
matrix.translate( self.transform_anchor_x, self.transform_anchor_y )
matrix.rotate( math.radians(-self.rotation) )
matrix.scale(self._scale, self._scale)
matrix.translate( -self.transform_anchor_x, -self.transform_anchor_y )
self.is_transform_dirty = False
self.transform_matrix = matrix
return self.transform_matrix
def get_world_transform( self ):
'''returns an euclid.Matrix3 with the world transformation matrix
:rtype: euclid.Matrix3
'''
matrix = self.get_local_transform()
p = self.parent
while p != None:
matrix = p.get_local_transform() * matrix
p = p.parent
return matrix
def point_to_world( self, p ):
'''returns an euclid.Vector2 converted to world space
:rtype: euclid.Vector2
'''
v = euclid.Point2( p[0], p[1] )
matrix = self.get_world_transform()
return matrix * v
def get_local_inverse( self ):
'''returns an euclid.Matrix3 with the local inverse transformation matrix
:rtype: euclid.Matrix3
'''
if self.is_inverse_transform_dirty:
matrix = self.get_local_transform().inverse()
self.inverse_transform_matrix = matrix
self.is_inverse_transform_dirty = False
return self.inverse_transform_matrix
def get_world_inverse( self ):
'''returns an euclid.Matrix3 with the world inverse transformation matrix
:rtype: euclid.Matrix3
'''
matrix = self.get_local_inverse()
p = self.parent
while p != None:
matrix = matrix * p.get_local_inverse()
p = p.parent
return matrix
def point_to_local( self, p ):
'''returns an euclid.Vector2 converted to local space
:rtype: euclid.Vector2
'''
v = euclid.Point2( p[0], p[1] )
matrix = self.get_world_inverse()
return matrix * v
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from pyglet.gl import *
from pyglet import window, image
import shader
__all__ = ['wired']
test_v = '''
varying vec3 position;
void main()
{
gl_Position = ftransform();
position = gl_Position.xyz;
}
'''
test_f = '''
uniform vec4 color;
void main()
{
gl_FragColor = color;
}
'''
def load_shader():
s = shader.ShaderProgram()
# s.setShader(shader.VertexShader('test_v', test_v))
s.setShader(shader.FragmentShader('test_f', test_f))
return s
wired = load_shader()
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
# Ideas borrowed from:
# Artificial Ineptitude : http://www.pyweek.org/e/0AI/
#
"""Here are a bunch of utilities to use with cocos.
utils
=====
This module provides classes or functions that were useful to us while doing games.
"""
__docformat__ = 'restructuredtext'
from cocos.layer import *
from cocos.scene import Scene
from cocos.director import director
class SequenceScene(Scene):
"""SequenceScene is used when you want to load more than one scene to the director.
Some easy example would be:
I want to run a Intro scene before the menu game. So I do this:
director.run( SequenceScene(intro(), menuGame()) )
"""
def __init__(self, *scenes):
super(SequenceScene, self).__init__()
self.scenes = scenes
self.p = 0
def on_enter(self):
if self.p >= len(self.scenes):
director.pop()
else:
director.push( self.scenes[ self.p ] )
self.p += 1
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from cocos import actions
from cocos import audio
class PlayAction(actions.InstantAction):
def init(self, sound):
self.sound = sound
def start(self):
if audio._working:
self.sound.play()
def __deepcopy__(self, memo):
# A shallow copy should be enough because sound effects are immutable
# Also, we don't need to use the memo, because there can not be a cycle
return PlayAction(self.sound)
| Python |
## pygame - Python Game Library
## Copyright (C) 2000-2003 Pete Shinners
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Library General Public
## License as published by the Free Software Foundation; either
## version 2 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
## Library General Public License for more details.
##
## You should have received a copy of the GNU Library General Public
## License along with this library; if not, write to the Free
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
## Pete Shinners
## pete@shinners.org
"""Simply the current installed pygame version. The version information is
stored in the regular pygame module as 'pygame.ver'. Keeping the version
information also available in a separate module allows you to test the
pygame version without importing the main pygame module.
The python version information should always compare greater than any previous
releases. (hmm, until we get to versions > 10)
"""
ver = '1.8.0pre'
vernum = 1,8,0
| Python |
#!/usr/bin/env python
'''Pygame module for controlling streamed audio
The music module is closely tied to pygame.mixer. Use the music module to
control the playback of music in the sound mixer.
The difference between the music playback and regular Sound playback is that
the music is streamed, and never actually loaded all at once. The mixer system
only supports a single music stream at once.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: music.py 875 2006-07-23 05:04:59Z aholkner $'
from cocos.audio.SDL import *
from cocos.audio.SDL.mixer import *
import base
import mixer
_current_music = None
_queue_music = None
_frequency = 0
_format = 0
_channels = 0
_pos = 0
_pos_time = -1
_endmusic_event = SDL_NOEVENT
def _mixmusic_callback(data, stream):
global _pos, _pos_time
if not Mix_PausedMusic():
_pos += len(stream)
_pos_time = SDL_GetTicks()
def _endmusic_callback():
global _current_music, _queue_music, _pos, _pos_time
if _endmusic_event:
_free_loaded(True, False)
_current_music = _queue_music
_queue_music = None
Mix_HookMusicFinished(_endmusic_callback)
_pos = 0
Mix_PlayMusic(_current_music, 0)
else:
_pos_time = -1
Mix_SetPostMix(None, None)
def _free_loaded(current=True, queue=True):
global _current_music, _queue_music
if current and _current_music:
Mix_FreeMusic(_current_music)
_current_music = None
if queue and _queue_music:
Mix_FreeMusic(_queue_music)
_current_music = None
def load(filename):
'''Load a music file for playback.
This will load a music file and prepare it for playback. If a music stream
is already playing it will be stopped. This does not start the music
playing.
Music can only be loaded from filenames, not python file objects like the
other pygame loading functions.
:Parameters:
`filename` : str
Filename of music to load.
'''
global _current_music
mixer._mixer_init_check()
_free_loaded()
_current_music = Mix_LoadMUS(filename)
def play(loops=0, start=0.0):
'''Start the playback of the music stream.
This will play the loaded music stream. If the music is already playing it
will be restarted.
The `loops` argument controls the number of repeats a music will play.
play(5) will cause the music to played once, then repeated five times, for
a total of six. If `loops` is -1 then the music will repeat until stopped.
The `start` argument controls where in the music the song starts playing.
The starting position is dependent on the format of music playing.
MP3 and OGG use the position as time (in seconds). MOD music it is the
pattern order number. Passing a value to `start` will raise a
NotImplementedError if it cannot set the start position
:Parameters:
`loops` : int
Number of times to repeat music after initial play through.
`start` : float
Starting time within music track to play from, in seconds.
'''
global _frequency, _format, _channels
mixer._mixer_init_check()
if not _current_music:
raise base.error, 'music not loaded'
Mix_HookMusicFinished(_endmusic_callback)
Mix_SetPostMix(_mixmusic_callback, None)
ready, _frequency, _format, _channels = Mix_QuerySpec()
if Mix_Linked_Version().is_since((1, 2, 3)):
volume = Mix_VolumeMusic(-1)
Mix_FadeInMusicPos(_current_music, loops, 0, start)
Mix_VolumeMusic(volume)
else:
if start:
raise NotImplementedError, \
'music start position requires SDL_Mixer 1.2.3 or later'
Mix_PlayMusic(_current_music, loops)
def rewind():
'''Restart music.
Resets playback of the current music to the beginning.
'''
mixer._mixer_init_check()
Mix_RewindMusic()
def stop():
'''Stop the music playback.
Stops the current music if it is playing. Any queued music will be
unqueued.
'''
mixer._mixer_init_check()
Mix_HaltMusic()
_free_loaded(False, True)
def pause():
'''Temporarily stop music playback.
Temporarily stop playback of the music stream. It can be resumed
with the `unpause` function.
'''
mixer._mixer_init_check()
Mix_PauseMusic()
def unpause():
'''Resume paused music.
This will resume the playback of a music stream after it has been paused.
'''
mixer._mixer_init_check()
Mix_UnpauseMusic()
def fadeout(time):
'''Stop music playback after fading out.
This will stop the music playback after it has been faded out over the
specified time (measured in milliseconds). Any queued music will be
unqueued.
Note, that this function blocks until the music has faded out.
:Parameters:
`time` : int
Time to fade out over, in milliseconds.
'''
mixer._mixer_init_check()
Mix_FadeOutMusic(time)
_free_loaded(False, True)
def set_volume(volume):
'''Set the music volume.
Set the volume of the music playback. The value argument is between
0.0 and 1.0. When new music is loaded the volume is reset.
:Parameters:
`volume` : float
Volume of music playback, in range [0.0, 1.0].
'''
mixer._mixer_init_check()
Mix_VolumeMusic(int(volume * 128))
def get_volume():
'''Get the music volume.
Returns the current volume for the mixer. The value will be between 0.0
and 1.0.
:rtype: float
'''
mixer._mixer_init_check()
return Mix_VolumeMusic(-1) / 128.0
def get_busy():
'''Check if the music stream is playing.
Returns True when the music stream is actively playing. When the music
is idle this returns False.
:rtype: bool
'''
mixer._mixer_init_check()
return Mix_PlayingMusic()
def get_pos():
'''Get the amount of time music has been playing.
This gets the number of milliseconds that the music has been playing for.
The returned time only represents how long the music has been playing; it
does not take into account any starting position offsets.
Returns -1 if the position is unknown.
:rtype: int
'''
mixer._mixer_init_check()
if _pos_time < 0:
return -1
ticks = 1000 * _pos / _channels / _frequency / ((_format & 0xff) >> 3)
if not Mix_PausedMusic():
ticks += SDL_GetTicks() - _pos_time
return int(ticks)
def queue(filename):
'''Queue a music file to follow the current one.
This will load a music file and queue it. A queued music file will begin
as soon as the current music naturally ends. If the current music is ever
stopped or changed, the queued song will be lost.
The following example will play music by Bach six times, then play
music by Mozart once::
pygame.mixer.music.load('bach.ogg')
pygame.mixer.music.play(5) # Plays six times, not five
pygame.mixer.music.queue('mozart.ogg')
:Parameters:
`filename` : str
Filename of music file to queue.
'''
global _queue_music
mixer._mixer_init_check()
music = Mix_LoadMUS(filename)
_free_loaded(False, True)
_queue_music = music
def set_endevent(eventtype=None):
'''Have the music send an event when playback stops.
This causes Pygame to signal (by means of the event queue) when
the music is done playing. The argument determines the type of
event that will be queued.
The event will be queued every time the music finishes, not just
the first time. To stop the event from being queued, call this
method with no argument.
:Parameters:
`eventtype` : int
Type of event to post. For example, ``SDL_USEREVENT + n``
'''
global _endmusic_event
if eventtype is None:
eventtype = SDL_NOEVENT
_endmusic_event = eventtype
def get_endevent():
'''Get the event a channel sends when playback stops.
Returns the event type to be sent every time the music finishes playback.
If there is no endevent the function returns pygame.NOEVENT.
:rtype: int
'''
return _endmusic_event
| Python |
#!/usr/bin/env python
'''Pygame module for loading and playing sounds.
This module contains classes for loading Sound objects and controlling
playback. The mixer module is optional and depends on SDL_mixer. Your
program should test that pygame.mixer is available and intialized before
using it.
The mixer module has a limited number of channels for playback of sounds.
Usually programs tell pygame to start playing audio and it selects an
available channel automatically. The default is 8 simultaneous channels,
but complex programs can get more precise control over the number of
channels and their use.
All sound playback is mixed in background threads. When you begin
to play a Sound object, it will return immediately while the sound
continues to play. A single Sound object can also be actively played
back multiple times.
The mixer also has a special streaming channel. This is for music
playback and is accessed through the pygame.mixer.music module.
The mixer module must be initialized like other pygame modules, but it has
some extra conditions. The pygame.mixer.init() function takes several
optional arguments to control the playback rate and sample size. Pygame
will default to reasonable values, but pygame cannot perform Sound
resampling, so the mixer should be initialized to match the values of
your audio resources.
NOTE: there is currently a bug on some windows machines which makes
sound play back 'scratchy'. There is not enough cpu in the sound
thread to feed the buffer to the sound api.
To get around this you can increase the buffer size. However this
means that there is more of a delay between the time you ask to play
the sound and when it gets played. Try calling this before the pygame.init or
pygame.mixer.init calls. pygame.mixer.pre_init(44100,-16,2, 1024 * 3)
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: mixer.py 928 2006-08-19 03:13:40Z aholkner $'
from cocos.audio.SDL import *
from cocos.audio.SDL.mixer import *
from cocos.audio.SDL.rwops import *
from cocos.audio.pygame import base
try:
from cocos.audio.pygame import music
_have_music = True
except ImportError:
_have_music = False
_request_frequency = MIX_DEFAULT_FREQUENCY
_request_size = MIX_DEFAULT_FORMAT
_request_stereo = MIX_DEFAULT_CHANNELS
_request_buffer = 1024
_channels = {}
import Queue
event_queue = Queue.Queue(256)
def __PYGAMEinit__(frequency=None, size=None, stereo=None, buffer=None):
if frequency is None:
frequency = _request_frequency
if size is None:
size = _request_size
if stereo is None:
stereo = _request_stereo
if buffer is None:
buffer = _request_buffer
stereo = min(2, stereo)
if size == 8:
size = AUDIO_U8
elif size == -8:
size = AUDIO_S8
elif size == 16:
size ==AUDIO_U16SYS
elif size == -16:
size = AUDIO_S16SYS
# Make buffer power of 2
i = 256
while i < buffer:
i <<= 1
buffer = i
global _endsound_callback
if not SDL_WasInit(SDL_INIT_AUDIO):
base.register_quit(_autoquit)
SDL_InitSubSystem(SDL_INIT_AUDIO)
Mix_OpenAudio(frequency, size, stereo, buffer)
if Mix_Linked_Version().is_since((1,2,3)):
Mix_ChannelFinished(_endsound_callback)
Mix_VolumeMusic(127)
return 1
def _autoquit():
global _channels
if SDL_WasInit(SDL_INIT_AUDIO):
Mix_HaltMusic()
_channels = {}
if _have_music:
music._free_loaded()
Mix_CloseAudio()
SDL_QuitSubSystem(SDL_INIT_AUDIO)
def _endsound_callback(channel):
channel = _channels.get(channel, None)
if not channel:
return
if channel._endevent != SDL_NOEVENT:
event_queue.put(channel)
if channel._queue:
channel._sound = channel._queue
channel._queue = None
channelnum = \
Mix_PlayChannelTimed(channel._id, channel._sound._chunk, 0, -1)
if channelnum != -1:
Mix_GroupChannel(channelnum, id(channel._sound))
else:
channel._sound = None
def init(frequency=None, size=None, stereo=None, buffer=None):
'''Initialize the mixer module.
Initialize the mixer module for Sound loading and playback. The default
arguments can be overridden to provide specific audio mixing. The size
argument represents how many bits are used for each audio sample. If the
value is negative then signed sample values will be used. Positive values
mean unsigned audio samples will be used. If the stereo argument is false
the mixer will use mono sound.
The buffer argument controls the number of internal samples used in the
sound mixer. The default value should work for most cases. It can be
lowered to reduce latency, but sound dropout may occur. It can be raised
to larger values to ensure playback never skips, but it will impose latency
on sound playback. The buffer size must be a power of two.
Some platforms require the pygame.mixer module to be initialized after the
display modules have initialized. The top level pygame.init() takes care
of this automatically, but cannot pass any arguments to the mixer init. To
solve this, mixer has a function pygame.mixer.pre_init() to set the proper
defaults before the toplevel init is used.
It is safe to call this more than once, but after the mixer is initialized
you cannot change the playback arguments without first calling
pygame.mixer.quit().
:Parameters:
`frequency` : int
Sample rate, in Hertz; defaults to 22050
`size` : int
Bits per sample per channel; defaults to -16. Positive values for
unsigned values, negative for signed.
`stereo` : int
Number of output channels: 1 for mono, 2 for stereo; defaults to
2.
`buffer` : int
Byte size of each output channel's buffer; a power of two;
defaults to 1024.
'''
__PYGAMEinit__(frequency, size, stereo, buffer)
def pre_init(frequency=0, size=0, stereo=0, buffer=0):
'''Preset the mixer init arguments.
Any nonzero arguments change the default values used when the real
pygame.mixer.init() is called. The best way to set custom mixer playback
values is to call pygame.mixer.pre_init() before calling the top level
pygame.init().
:Parameters:
`frequency` : int
Sample rate, in Hertz
`size` : int
Bits per sample per channel. Positive values for unsigned
values, negative for signed.
`stereo` : bool
Number of mixdown channels: False for 1, True for 2.
`buffer` : int
Bytes for mixdown buffer size; a power of two.
'''
global _request_frequency
global _request_size
global _request_stereo
global _request_buffer
if frequency:
_request_frequency = frequency
if size:
_request_size = size
if stereo:
_request_stereo = stereo
if buffer:
_request_buffer = buffer
def quit():
'''Uninitialize the mixer.
This will uninitialize pygame.mixer. All playback will stop and any loaded
Sound objects may not be compatable with the mixer if it is reinitialized
later.
'''
_autoquit()
def get_init():
'''Determine if the mixer is initialized.
If the mixer is initialized, this returns the playback arguments it
is using. If the mixer has not been initialized this returns None
The value of `size` follows the same conventions as in `init`.
:rtype: (int, int, bool) or None
:return: (frequency, size, stereo)
'''
if not SDL_WasInit(SDL_INIT_AUDIO):
return
opened, frequency, format, channels = Mix_QuerySpec()
if format & ~0xff:
format = -(format & 0xff)
return frequency, format, channels > 1
def _mixer_init_check():
if not SDL_WasInit(SDL_INIT_AUDIO):
raise base.error, 'mixer system not initialized'
def stop():
'''Stop playback of all sound channels.
This will stop all playback of all active mixer channels.
'''
_mixer_init_check()
Mix_HaltChannel(-1)
def pause():
'''Temporarily stop playback of all sound channels.
This will temporarily stop all playback on the active mixer channels.
The playback can later be resumed with pygame.mixer.unpause()
'''
_mixer_init_check()
Mix_Pause(-1)
def unpause():
'''Resume paused playback of sound channels.
This will resume all active sound channels after they have been paused.
'''
_mixer_init_check()
Mix_Resume(-1)
def fadeout(time):
'''Fade out the volume on all sounds before stopping.
This will fade out the volume on all active channels over the time
argument in milliseconds. After the sound is muted the playback will stop.
:Parameters:
`time` : int
Time to fade out, in milliseconds.
'''
_mixer_init_check()
Mix_FadOutChannel(-1, time)
def set_num_channels(channels):
'''Set the total number of playback channels.
Sets the number of available channels for the mixer. The default value is
8. The value can be increased or decreased. If the value is decreased,
sounds playing on the truncated channels are stopped.
:Parameters:
`channels` : int
Number of channels
'''
_mixer_init_check()
Mix_AllocateChannels(channels)
for i in _channels.keys()[:]:
if i >= channels:
del channels[i]
def get_num_channels():
'''Get the total number of playback channels.
Returns the number of currently active playback channels.
:rtype: int
'''
_mixer_init_check()
return Mix_GroupCount(-1)
def set_reserved(channels):
'''Reserve channels from being automatically used.
The mixer can reserve any number of channels that will not be automatically
selected for playback by Sounds. If sounds are currently playing on the
reserved channels they will not be stopped.
This allows the application to reserve a specific number of channels for
important sounds that must not be dropped or have a guaranteed channel to
play on.
:Parameters:
`channels` : int
Number of channels to reserve.
'''
_mixer_init_check()
Mix_ReserveChannels(channels)
def find_channel(force=False):
'''Find an unused channel.
This will find and return an inactive Channel object. If there are no
inactive Channels this function will return None. If there are no inactive
channels and the force argument is True, this will find the Channel with
the longest running Sound and return it.
If the mixer has reserved channels from pygame.mixer.set_reserved() then
those channels will not be returned here.
:Parameters:
`force` : bool
If True, a playing channel will be returned if no free ones
are available.
:rtype: `Channel`
'''
_mixer_init_check()
chan = Mix_GroupAvailable(-1)
if chan == -1:
if not force:
return
chan = Mix_GroupOldest(-1)
return Channel(chan)
def get_busy():
'''Test if any sound is being mixed.
Returns True if the mixer is busy mixing any channels. If the mixer is
idle then this return False.
:rtype: bool
'''
if not SDL_WasInit(SDL_INIT_AUDIO):
return False
return bool(Mix_Playing(-1))
class Sound(object):
'''The Sound object represents actual sound sample data.
Methods that change the state of the Sound object will the all instances
of the Sound playback.
'''
__slots__ = ['_chunk']
def __init__(self, file, _chunk=None):
'''Create a new Sound object from a file.
Load a new sound buffer from a filename or from a python file object.
Limited resampling will be performed to help the sample match the
initialize arguments for the mixer.
The Sound can be loaded from an OGG audio file or from an uncompressed
WAV.
:Parameters:
`file` : str or file-like object
The filename or file to load.
`_chunk` : None
Internal use only.
'''
if _chunk:
self._chunk = _chunk
return
_mixer_init_check()
if hasattr(file, 'read'):
rw = SDL_RWFromObject(file)
# differ from Pygame, no freesrc here.
self._chunk = Mix_LoadWAV_RW(rw, 0)
else:
self._chunk = Mix_LoadWAV(file)
def __del__(self):
if self._chunk:
Mix_FreeChunk(self._chunk)
def play(self, loops=0, maxtime=-1):
'''Begin sound playback.
Begin playback of the Sound (i.e., on the computer's speakers) on an
available Channel. This will forcibly select a Channel, so playback
may cut off a currently playing sound if necessary.
The loops argument controls how many times the sample will be repeated
after being played the first time. A value of 5 means that the sound
will be played once, then repeated five times, and so is played a
total of six times. The default value (zero) means the Sound is not
repeated, and so is only played once. If loops is set to -1 the Sound
will loop indefinitely (though you can still call stop() to stop it).
The maxtime argument can be used to stop playback after a given number
of milliseconds.
:Parameters:
`loops` : int
Number of times to repeat the sound after the first play.
`maxtime` : int
Maximum number of milliseconds to play for.
:rtype: `Channel`
:return: The Channel object for the channel that was selected.
'''
channelnum = Mix_PlayChannelTimed(-1, self._chunk, loops, maxtime)
if channelnum == -1:
return
Mix_Volume(channelnum, 128)
Mix_GroupChannel(channelnum, id(self))
channel = Channel(channelnum)
channel._queue = None
channel._sound = self
return channel
def stop(self):
'''Stop sound playback.
This will stop the playback of this Sound on any active Channels.
'''
_mixer_init_check()
Mix_HaltGroup(id(self))
def fadeout(self, time):
'''Stop sound playback after fading out.
This will stop playback of the sound after fading it out over the
time argument in milliseconds. The Sound will fade and stop on all
actively playing channels.
:Parameters:
`time` : int
Time to fade out, in milliseconds.
'''
_mixer_init_check()
Mix_FadeOutGroup(id(self), time)
def set_volume(self, volume):
'''Set the playback volume for this Sound.
This will set the playback volume (loudness) for this Sound. This will
immediately affect the Sound if it is playing. It will also affect any
future playback of this Sound. The argument is a value from 0.0 to
1.0.
:Parameters:
`volume` : float
Volume of playback, in range [0.0, 1.0]
'''
_mixer_init_check()
Mix_VolumeChunk(self._chunk, int(volume * 128))
def get_volume(self):
'''Get the playback volume.
Return a value from 0.0 to 1.0 representing the volume for this Sound.
:rtype: float
'''
_mixer_init_check()
return Mix_VolumeChunk(self._chunk, -1) / 128.0
def get_num_channels(self):
'''Count how many times this Sound is playing.
Return the number of active channels this sound is playing on.
:rtype: int
'''
_mixer_init_check()
return Mix_GroupCount(id(self))
def get_length(self):
'''Get the length of the Sound.
Return the length of this Sound in seconds.
:rtype: float
'''
_mixer_init_check()
opened, freq, format, channels = Mix_QuerySpec()
if format == AUDIO_S8 or format == AUDIO_U8:
mixerbytes = 1
else:
mixerbytes = 2
numsamples = self._chunk.alen / mixerbytes / channels
return numsamples / float(freq)
class Channel(object):
'''The Channel object can be used to get fine control over the playback of
Sounds. A channel can only playback a single Sound at time. Using channels
is entirely optional since pygame can manage them by default.
'''
__slots__ = ['_id', '_sound', '_queue', '_endevent']
def __new__(cls, id):
_mixer_init_check()
if id < 0 or id >= Mix_GroupCount(-1):
raise IndexError, 'invalid channel index'
if id in _channels:
return _channels[id]
inst = super(Channel, cls).__new__(cls)
return inst
def __init__(self, id):
'''Create a Channel object for controlling playback.
Create a Channel object for one of the current channels. The id must
be a value from 0 to the value of pygame.mixer.get_num_channels().
:Parameters:
`id` : int
ID of existing channel to create object for.
'''
self._id = id
if id not in _channels:
self._sound = None
self._queue = None
self._endevent = SDL_NOEVENT
_channels[id] = self
def play(self, sound, loops=0, time=-1):
'''Play a Sound on a specific Channel.
This will begin playback of a Sound on a specific Channel. If the
Channel is currently playing any other Sound it will be stopped.
The loops argument has the same meaning as in Sound.play(): it is the
number of times to repeat the sound after the first time. If it is 3,
the sound will be played 4 times (the first time, then three more).
If loops is -1 then the playback will repeat indefinitely.
As in Sound.play(), the time argument can be used to
stop playback of the Sound after a given number of milliseconds.
:Parameters:
`sound` : `Sound`
Sound data to play.
`loops` : int
Number of times to repeat the sound after the first play.
`time` : int
Maximum number of milliseconds to play for.
'''
channelnum = Mix_PlayChannelTimed(self._id, sound._chunk, loops, time)
if channelnum != -1:
Mix_GroupChannel(channelnum, id(sound))
self._sound = sound
self._queue = None
def stop(self):
'''Stop playback on a Channel.
Stop sound playback on a channel. After playback is stopped the
channel becomes available for new Sounds to play on it.
'''
_mixer_init_check()
Mix_HaltChannel(self._id)
def pause(self):
'''Temporarily stop playback of a channel.
Temporarily stop the playback of sound on a channel. It can be resumed
at a later time with Channel.unpause()
'''
_mixer_init_check()
Mix_Pause(self._id)
def unpause(self):
'''Resume pause playback of a channel.
Resume the playback on a paused channel.
'''
_mixer_init_check()
Mix_Resume(self._id)
def fadeout(self, time):
'''Stop playback after fading channel out.
Stop playback of a channel after fading out the sound over the given
time argument in milliseconds.
:Parameters:
`time` : int
Time to fade out, in milliseconds.
'''
_mixer_init_check()
Mix_FadeOutChannel(self._id, time)
def set_volume(self, left, right=None):
'''Set the volume of a playing channel.
Set the volume (loudness) of a playing sound. When a channel starts to
play its volume value is reset. This only affects the current sound.
Each argument is between 0.0 and 1.0.
If one argument is passed, it will be the volume of both speakers.
If two arguments are passed and the mixer is in stereo mode, the
first argument will be the volume of the left speaker and the second
will be the volume of the right speaker. (If the second argument is
None, the first argument will be the volume of both speakers.)
If the channel is playing a Sound on which set_volume() has also
been called, both calls are taken into account. For example::
sound = pygame.mixer.Sound("s.wav")
channel = s.play() # Sound plays at full volume by default
sound.set_volume(0.9) # Now plays at 90% of full volume.
sound.set_volume(0.6) # Now plays at 60% (previous value replaced)
channel.set_volume(0.5) # Now plays at 30% (0.6 * 0.5).
:Parameters:
`left` : float
Volume of left (or mono) channel, in range [0.0, 1.0]
`right` : float
Volume of right channel, in range [0.0, 1.0]
'''
_mixer_init_check()
if Mix_Linked_Version().is_since((1,2,1)):
if right is None:
Mix_SetPanning(self._id, 255, 255)
else:
Mix_SetPanning(self._id, int(left * 255), int(right * 255))
left = 1.0
else:
if right is not None:
left = (left + right) / 2
Mix_Volume(self._id, int(left * 128))
def get_volume(self):
'''Get the volume of the playing channel.
Return the volume of the channel for the current playing sound. This
does not take into account stereo separation used by
Channel.set_volume. The Sound object also has its own volume which is
mixed with the channel.
:rtype: float
'''
_mixer_init_check()
return Mix_Volume(self._id, -1) / 128.0
def get_busy(self):
'''Determine if the channel is active.
Returns true if the channel is activily mixing sound. If the channel
is idle this returns False.
:rtype: bool
'''
_mixer_init_check()
return Mix_Playing(self._id)
def get_sound(self):
'''Get the currently playing Sound.
Return the actual Sound object currently playing on this channel. If
the channel is idle None is returned.
:rtype: `Sound`
'''
return self._sound
def queue(self, sound):
'''Queue a Sound object to follow the current.
When a Sound is queued on a Channel, it will begin playing immediately
after the current Sound is finished. Each channel can only have a
single Sound queued at a time. The queued Sound will only play if the
current playback finished automatically. It is cleared on any other
call to Channel.stop() or Channel.play().
If there is no sound actively playing on the Channel then the Sound
will begin playing immediately.
:Parameters:
`sound` : `Sound`
Sound data to queue.
'''
if not self._sound:
channelnum = Mix_PlayChannelTimed(self._id, sound._chunk, 0, -1)
if channelnum != -1:
Mix_GroupChannel(channelnum, id(sound))
self._sound = sound
else:
self._queue = sound
def get_queue(self):
'''Return any Sound that is queued.
If a Sound is already queued on this channel it will be returned. Once
the queued sound begins playback it will no longer be on the queue.
:rtype: `Sound`
'''
return self._queue
def set_endevent(self, id=None):
'''Have the channel send an event when playback stops.
When an endevent is set for a channel, it will send an event to the
pygame queue every time a sound finishes playing on that channel (not
just the first time). Use pygame.event.get() to retrieve the endevent
once it's sent.
Note that if you called Sound.play(n) or Channel.play(sound,n), the
end event is sent only once: after the sound has been played "n+1"
times (see the documentation of Sound.play).
If Channel.stop() or Channel.play() is called while the sound was
still playing, the event will be posted immediately.
The `id` argument will be the event id sent to the queue. This can be
any valid event type, but a good choice would be a value between
pygame.locals.USEREVENT and pygame.locals.NUMEVENTS. If no type
argument is given then the Channel will stop sending endevents.
:Parameters:
`id` : int
Event ID to send.
'''
if id is None:
id = SDL_NOEVENT
self._endevent = id
def get_endevent(self):
'''Get the event a channel sends when playback stops.
Returns the event type to be sent every time the Channel finishes
playback of a Sound. If there is no endevent the function returns
pygame.NOEVENT.
:rtype: int
'''
return self._endevent
| Python |
#!/usr/bin/env python
'''Pygame core routines
Contains the core routines that are used by the rest of the
pygame modules. Its routines are merged directly into the pygame
namespace. This mainly includes the auto-initialization `init` and
`quit` routines.
There is a small module named `locals` that also gets merged into
this namespace. This contains all the constants needed by pygame.
Object constructors also get placed into this namespace, you can
call functions like `Rect` and `Surface` to create objects of
that type. As a convenience, you can import the members of
pygame.locals directly into your module's namespace with::
from pygame.locals import *
Most of the pygame examples do this if you'd like to take a look.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: base.py 911 2006-08-09 08:56:31Z aholkner $'
import atexit
import sys
from cocos.audio import SDL
_quitfunctions = []
class error(RuntimeError):
pass
def init():
'''Autoinitialize all imported pygame modules.
Initialize all imported pygame modules. Includes pygame modules
that are not part of the base modules (like font and image).
It does not raise exceptions, but instead silently counts which
modules have failed to init. The return argument contains a count
of the number of modules initialized, and the number of modules
that failed to initialize.
You can always initialize the modules you want by hand. The
modules that need it have an `init` and `quit` routine built in,
which you can call directly. They also have a `get_init` routine
which you can use to doublecheck the initialization. Note that
the manual `init` routines will raise an exception on error. Be
aware that most platforms require the display module to be
initialized before others. This `init` will handle that for you,
but if you initialize by hand, be aware of this constraint.
As with the manual `init` routines. It is safe to call this
`init` as often as you like.
:rtype: int, int
:return: (count_passed, count_failed)
'''
success = 0
fail = 0
SDL.SDL_Init(SDL.SDL_INIT_EVENTTHREAD | \
SDL.SDL_INIT_TIMER | \
SDL.SDL_INIT_NOPARACHUTE)
if _video_autoinit():
success += 1
else:
fail += 1
for mod in sys.modules.values():
if hasattr(mod, '__PYGAMEinit__') and callable(mod.__PYGAMEinit__):
try:
mod.__PYGAMEinit__()
success += 1
except:
fail += 1
return success, fail
def register_quit(func):
'''Routine to call when pygame quits.
The given callback routine will be called when pygame is
quitting. Quit callbacks are served on a 'last in, first out'
basis.
'''
_quitfunctions.append(func)
def _video_autoquit():
if SDL.SDL_WasInit(SDL.SDL_INIT_VIDEO):
SDL.SDL_QuitSubSystem(SDL.SDL_INIT_VIDEO)
def _video_autoinit():
if not SDL.SDL_WasInit(SDL.SDL_INIT_VIDEO):
SDL.SDL_InitSubSystem(SDL.SDL_INIT_VIDEO)
SDL.SDL_EnableUNICODE(1)
return 1
def _atexit_quit():
while _quitfunctions:
func = _quitfunctions.pop()
func()
_video_autoquit()
SDL.SDL_Quit()
def get_sdl_version():
'''Get the version of the linked SDL runtime.
:rtype: int, int, int
:return: major, minor, patch
'''
v = SDL.SDL_Linked_Version()
return v.major, v.minor, v.patch
def quit():
'''Uninitialize all pygame modules.
Uninitialize all pygame modules that have been initialized. Even
if you initialized the module by hand, this `quit` will
uninitialize it for you.
All the pygame modules are uninitialized automatically when your
program exits, so you will usually not need this routine. If you
program plans to keep running after it is done with pygame, then
would be a good time to make this call.
'''
_atexit_quit()
def get_error():
'''Get current error message.
SDL maintains an internal current error message. This message is
usually given to you when an SDL related exception occurs, but
sometimes you may want to call this directly yourself.
:rtype: str
'''
return SDL.SDL_GetError()
def _rgba_from_obj(obj):
if not type(obj) in (tuple, list):
return None
if len(obj) == 1:
return _rgba_from_obj(obj[0])
elif len(obj) == 3:
return (int(obj[0]), int(obj[1]), int(obj[2]), 255)
elif len(obj) == 4:
return obj
else:
return None
atexit.register(_atexit_quit)
| Python |
## pygame - Python Game Library
## Copyright (C) 2000-2001 Pete Shinners
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Library General Public
## License as published by the Free Software Foundation; either
## version 2 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
## Library General Public License for more details.
##
## You should have received a copy of the GNU Library General Public
## License along with this library; if not, write to the Free
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
## Pete Shinners
## pete@shinners.org
'''Top-level Pygame module.
Pygame is a set of Python modules designed for writing games.
It is written on top of the excellent SDL library. This allows you
to create fully featured games and multimedia programs in the Python
language. The package is highly portable, with games running on
Windows, MacOS, OS X, BeOS, FreeBSD, IRIX, and Linux.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: __init__.py 899 2006-08-04 16:52:18Z aholkner $'
import os
import sys
class MissingModule:
def __init__(self, name, info='', urgent=0):
self.name = name
self.info = str(info)
self.urgent = urgent
if urgent:
self.warn()
def __getattr__(self, var):
if not self.urgent:
self.warn()
self.urgent = 1
MissingPygameModule = "%s module not available" % self.name
raise NotImplementedError, MissingPygameModule
def __nonzero__(self):
return 0
def warn(self):
if self.urgent: type = 'import'
else: type = 'use'
message = '%s %s: %s' % (type, self.name, self.info)
try:
import warnings
if self.urgent: level = 4
else: level = 3
warnings.warn(message, RuntimeWarning, level)
except ImportError:
print message
#we need to import like this, each at a time. the cleanest way to import
#our modules is with the import command (not the __import__ function)
#first, the "required" modules
#from pygame.array import *
from cocos.audio.pygame.base import *
from cocos.audio.pygame.version import *
__version__ = ver
#next, the "standard" modules
#we still allow them to be missing for stripped down pygame distributions
try: import cocos.audio.pygame.mixer
except (ImportError,IOError), msg:mixer=MissingModule("mixer", msg, 0)
#there's also a couple "internal" modules not needed
#by users, but putting them here helps "dependency finder"
#programs get everything they need (like py2exe)
try: import cocos.audio.pygame.mixer_music; del cocos.audio.pygame.mixer_music
except (ImportError,IOError):pass
#cleanup namespace
del os, sys, #TODO rwobject, surflock, MissingModule, copy_reg
| Python |
#!/usr/bin/env python
'''Time management routines.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
import dll
SDL_GetTicks = dll.function('SDL_GetTicks',
'''Get the number of milliseconds since the SDL library initialization.
Note that this value wraps if the program runs for more than ~49 days.
:rtype: int
''',
args=[],
arg_types=[],
return_type=c_uint)
SDL_Delay = dll.function('SDL_Delay',
'''Wait a specified number of milliseconds before returning.
:Parameters:
`ms` : int
delay in milliseconds
''',
args=['ms'],
arg_types=[c_uint],
return_type=None)
_SDL_TimerCallback = CFUNCTYPE(c_int, c_uint)
_SDL_SetTimer = dll.private_function('SDL_SetTimer',
arg_types=[c_uint, _SDL_TimerCallback],
return_type=c_int)
_timercallback_ref = None # Keep global to avoid possible GC
def SDL_SetTimer(interval, callback):
'''Set a callback to run after the specified number of milliseconds has
elapsed.
The callback function is passed the current timer interval
and returns the next timer interval. If the returned value is the
same as the one passed in, the periodic alarm continues, otherwise a
new alarm is scheduled. If the callback returns 0, the periodic alarm
is cancelled.
To cancel a currently running timer, call ``SDL_SetTimer(0, None)``.
The timer callback function may run in a different thread than your
main code, and so shouldn't call any functions from within itself.
The maximum resolution of this timer is 10 ms, which means that if
you request a 16 ms timer, your callback will run approximately 20 ms
later on an unloaded system. If you wanted to set a flag signaling
a frame update at 30 frames per second (every 33 ms), you might set a
timer for 30 ms::
SDL_SetTimer((33/10)*10, flag_update)
If you use this function, you need to pass `SDL_INIT_TIMER` to
`SDL_Init`.
Under UNIX, you should not use raise or use SIGALRM and this function
in the same program, as it is implemented using ``setitimer``. You
also should not use this function in multi-threaded applications as
signals to multi-threaded apps have undefined behavior in some
implementations.
:Parameters:
`interval` : int
Interval before callback, in milliseconds.
`callback` : function
Callback function should accept one argument, the number of
milliseconds elapsed, and return the next timer interval,
in milliseconds.
'''
# Note SDL_SetTimer actually returns 1 on success, not 0 as documented
# in SDL_timer.h.
global _timercallback_ref
if callback:
_timercallback_ref = _SDL_TimerCallback(callback)
else:
_timercallback_ref = _SDL_TimerCallback()
# XXX if this fails the global ref is incorrect and old one will
# possibly be collected early.
if _SDL_SetTimer(interval, _timercallback_ref) == -1:
raise SDL.error.SDL_Exception, SDL.error.SDL_GetError()
# For the new timer functions, the void *param passed to the callback
# is ignored; using an local function instead. The SDL_TimerID type
# is not defined, we use c_void_p instead.
_SDL_NewTimerCallback = CFUNCTYPE(c_uint, c_int, c_void_p)
_SDL_AddTimer = dll.private_function('SDL_AddTimer',
arg_types=[c_uint, _SDL_NewTimerCallback, c_void_p],
return_type=c_void_p)
_timer_refs = {} # Keep global to manage GC
def SDL_AddTimer(interval, callback, param):
'''Add a new timer to the pool of timers already running.
:Parameters:
`interval` : int
The interval before calling the callback, in milliseconds.
`callback` : function
The callback function. It is passed the current timer
interval, in millseconds, and returns the next timer interval,
in milliseconds. If the returned value is the same as the one
passed in, the periodic alarm continues, otherwise a new alarm
is scheduled. If the callback returns 0, the periodic alarm is
cancelled. An example callback function is::
def timer_callback(interval, param):
print 'timer called after %d ms.' % interval
return 1000 # call again in 1 second
`param` : any
A value passed to the callback function.
:rtype: int
:return: the timer ID
'''
def _callback(interval, _ignored_param):
return callback(interval, param)
func = _SDL_NewTimerCallback(_callback)
result = _SDL_AddTimer(interval, func, None)
if not result:
raise SDL.error.SDL_Exception, SDL.error.SDL_GetError()
_timer_refs[result] = func
return result
_SDL_RemoveTimer = dll.private_function('SDL_RemoveTimer',
args=['t'],
arg_types=[c_void_p],
return_type=c_int,
error_return=0)
def SDL_RemoveTimer(t):
'''Remove one of the multiple timers knowing its ID.
:Parameters:
`t` : int
The timer ID, as returned by `SDL_AddTimer`.
'''
global _timer_refs
_SDL_RemoveTimer(t)
del _timer_refs[t]
| Python |
#!/usr/bin/env python
'''An abstract sound format decoding API.
The latest version of SDL_sound can be found at: http://icculus.org/SDL_sound/
The basic gist of SDL_sound is that you use an SDL_RWops to get sound data
into this library, and SDL_sound will take that data, in one of several
popular formats, and decode it into raw waveform data in the format of
your choice. This gives you a nice abstraction for getting sound into your
game or application; just feed it to SDL_sound, and it will handle
decoding and converting, so you can just pass it to your SDL audio
callback (or whatever). Since it gets data from an SDL_RWops, you can get
the initial sound data from any number of sources: file, memory buffer,
network connection, etc.
As the name implies, this library depends on SDL: Simple Directmedia Layer,
which is a powerful, free, and cross-platform multimedia library. It can
be found at http://www.libsdl.org/
Support is in place or planned for the following sound formats:
- .WAV (Microsoft WAVfile RIFF data, internal.)
- .VOC (Creative Labs' Voice format, internal.)
- .MP3 (MPEG-1 Layer 3 support, via the SMPEG and mpglib libraries.)
- .MID (MIDI music converted to Waveform data, internal.)
- .MOD (MOD files, via MikMod and ModPlug.)
- .OGG (Ogg files, via Ogg Vorbis libraries.)
- .SPX (Speex files, via libspeex.)
- .SHN (Shorten files, internal.)
- .RAW (Raw sound data in any format, internal.)
- .AU (Sun's Audio format, internal.)
- .AIFF (Audio Interchange format, internal.)
- .FLAC (Lossless audio compression, via libFLAC.)
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
import cocos.audio.SDL.array
import cocos.audio.SDL.dll
import cocos.audio.SDL.rwops
import cocos.audio.SDL.version
SDL = cocos.audio.SDL
_dll = SDL.dll.SDL_DLL('SDL_sound', None, '1.2')
class Sound_Version(Structure):
'''Version structure.
:Ivariables:
`major` : int
Major version number
`minor` : int
Minor version number
`patch` : int
Patch revision number
'''
_fields_ = [('major', c_int),
('minor', c_int),
('patch', c_int)]
def __repr__(self):
return '%d.%d.%d' % (self.major, self.minor, self.patch)
_Sound_GetLinkedVersion = _dll.private_function('Sound_GetLinkedVersion',
arg_types=[POINTER(Sound_Version)],
return_type=None)
def Sound_GetLinkedVersion():
'''Get the version of the dynamically linked SDL_sound library
:rtype: `Sound_Version`
'''
version = Sound_Version()
_Sound_GetLinkedVersion(byref(version))
return version
# Fill in non-standard linked version now, so "since" declarations can work
_dll._version = SDL.dll._version_parts(Sound_GetLinkedVersion())
class Sound_AudioInfo(Structure):
'''Information about an existing sample's format.
:Ivariables:
`format` : int
Equivalent to `SDL_AudioSpec.format`
`channels` : int
Number of sound channels. 1 == mono, 2 == stereo.
`rate` : int
Sample rate, in samples per second.
:see: `Sound_SampleNew`
:see: `Sound_SampleNewFromFile`
'''
_fields_ = [('format', c_ushort),
('channels', c_ubyte),
('rate', c_uint)]
class Sound_DecoderInfo(Structure):
'''Information about a sound decoder.
Each decoder sets up one of these structures, which can be retrieved
via the `Sound_AvailableDecoders` function. Fields in this
structure are read-only.
:Ivariables:
`extensions` : list of str
List of file extensions
`description` : str
Human-readable description of the decoder
`author` : str
Author and email address
`url` : str
URL specific to this decoder
'''
_fields_ = [('_extensions', POINTER(c_char_p)),
('description', c_char_p),
('author', c_char_p),
('url', c_char_p)]
def __getattr__(self, name):
if name == 'extensions':
extensions = []
ext_p = self._extensions
i = 0
while ext_p[i]:
extensions.append(ext_p[i])
i += 1
return extensions
raise AttributeError, name
class Sound_Sample(Structure):
'''Represents sound data in the process of being decoded.
The `Sound_Sample` structure is the heart of SDL_sound. This holds
information about a source of sound data as it is beind decoded. All
fields in this structure are read-only.
:Ivariables:
`decoder` : `Sound_DecoderInfo`
Decoder used for this sample
`desired` : `Sound_AudioInfo`
Desired audio format for conversion
`actual` : `Sound_AudioInfo`
Actual audio format of the sample
`buffer` : `SDL_array`
Buffer of decoded data, as bytes
`buffer_size` : int
Current size of the buffer, in bytes
`flags` : int
Bitwise combination of SOUND_SAMPLEFLAG_CANSEEK,
SOUND_SAMPLEFLAG_EOF, SOUND_SAMPLEFLAG_ERROR,
SOUND_SAMPLEFLAG_EGAIN
'''
_fields_ = [('opaque', c_void_p),
('_decoder', POINTER(Sound_DecoderInfo)),
('desired', Sound_AudioInfo),
('actual', Sound_AudioInfo),
('_buffer', POINTER(c_ubyte)),
('buffer_size', c_uint),
('flags', c_int)]
def __getattr__(self, name):
if name == 'decoder':
return self._decoder.contents
elif name == 'buffer':
return SDL.array.SDL_array(self._buffer, self.buffer_size, c_ubyte)
raise AttributeError, name
Sound_Init = _dll.function('Sound_Init',
'''Initialize SDL_sound.
This must be called before any other SDL_sound function (except perhaps
`Sound_GetLinkedVersion`). You should call `SDL_Init` before calling
this. `Sound_Init` will attempt to call ``SDL_Init(SDL_INIT_AUDIO)``,
just in case. This is a safe behaviour, but it may not configure SDL
to your liking by itself.
''',
args=[],
arg_types=[],
return_type=c_int,
error_return=0)
Sound_Quit = _dll.function('Sound_Quit',
'''Shutdown SDL_sound.
This closes any SDL_RWops that were being used as sound sources, and
frees any resources in use by SDL_sound.
All Sound_Sample structures existing will become invalid.
Once successfully deinitialized, `Sound_Init` can be called again to
restart the subsystem. All default API states are restored at this
point.
You should call this before `SDL_Quit`. This will not call `SDL_Quit`
for you.
''',
args=[],
arg_types=[],
return_type=c_int,
error_return=0)
_Sound_AvailableDecoders = _dll.private_function('Sound_AvailableDecoders',
arg_types=[],
return_type=POINTER(POINTER(Sound_DecoderInfo)))
def Sound_AvailableDecoders():
'''Get a list of sound formats supported by this version of SDL_sound.
This is for informational purposes only. Note that the extension listed
is merely convention: if we list "MP3", you can open an MPEG-1 Layer 3
audio file with an extension of "XYZ", if you like. The file extensions
are informational, and only required as a hint to choosing the correct
decoder, since the sound data may not be coming from a file at all,
thanks to the abstraction that an SDL_RWops provides.
:rtype: list of `Sound_DecoderInfo`
'''
decoders = []
decoder_p = _Sound_AvailableDecoders()
i = 0
while decoder_p[i]:
decoders.append(decoder_p[i].contents)
i += 1
return decoders
Sound_GetError = _dll.function('Sound_GetError',
'''Get the last SDL_sound error message.
This will be None if there's been no error since the last call to this
function. Each thread has a unique error state associated with it, but
each time a new error message is set, it will overwrite the previous
one associated with that thread. It is safe to call this function at
any time, even before `Sound_Init`.
:rtype: str
''',
args=[],
arg_types=[],
return_type=c_char_p)
Sound_ClearError = _dll.function('Sound_ClearError',
'''Clear the current error message.
The next call to `Sound_GetError` after `Sound_ClearError` will return
None.
''',
args=[],
arg_types=[],
return_type=None)
Sound_NewSample = _dll.function('Sound_NewSample',
'''Start decoding a new sound sample.
The data is read via an SDL_RWops structure, so it may be coming from
memory, disk, network stream, etc. The `ext` parameter is merely a hint
to determining the correct decoder; if you specify, for example, "mp3"
for an extension, and one of the decoders lists that as a handled
extension, then that decoder is given first shot at trying to claim the
data for decoding. If none of the extensions match (or the extension is
None), then every decoder examines the data to determine if it can
handle it, until one accepts it. In such a case your SDL_RWops will
need to be capable of rewinding to the start of the stream.
If no decoders can handle the data, an exception is raised.
Optionally, a desired audio format can be specified. If the incoming data
is in a different format, SDL_sound will convert it to the desired format
on the fly. Note that this can be an expensive operation, so it may be
wise to convert data before you need to play it back, if possible, or
make sure your data is initially in the format that you need it in.
If you don't want to convert the data, you can specify None for a desired
format. The incoming format of the data, preconversion, can be found
in the `Sound_Sample` structure.
Note that the raw sound data "decoder" needs you to specify both the
extension "RAW" and a "desired" format, or it will refuse to handle
the data. This is to prevent it from catching all formats unsupported
by the other decoders.
Finally, specify an initial buffer size; this is the number of bytes that
will be allocated to store each read from the sound buffer. The more you
can safely allocate, the more decoding can be done in one block, but the
more resources you have to use up, and the longer each decoding call will
take. Note that different data formats require more or less space to
store. This buffer can be resized via `Sound_SetBufferSize`.
The buffer size specified must be a multiple of the size of a single
sample point. So, if you want 16-bit, stereo samples, then your sample
point size is (2 channels 16 bits), or 32 bits per sample, which is four
bytes. In such a case, you could specify 128 or 132 bytes for a buffer,
but not 129, 130, or 131 (although in reality, you'll want to specify a
MUCH larger buffer).
When you are done with this `Sound_Sample` instance, you can dispose of
it via `Sound_FreeSample`.
You do not have to keep a reference to `rw` around. If this function
suceeds, it stores `rw` internally (and disposes of it during the call
to `Sound_FreeSample`). If this function fails, it will dispose of the
SDL_RWops for you.
:Parameters:
`rw` : `SDL_RWops`
SDL_RWops with sound data
`ext` : str
File extension normally associated with a data format. Can
usually be None.
`desired` : `Sound_AudioInfo`
Format to convert sound data into. Can usually be None if you
don't need conversion.
`bufferSize` : int
Size, in bytes, to allocate for the decoding buffer
:rtype: `Sound_Sample`
''',
args=['rw', 'ext', 'desired', 'bufferSize'],
arg_types=[POINTER(SDL.rwops.SDL_RWops), c_char_p,
POINTER(Sound_AudioInfo), c_uint],
return_type=POINTER(Sound_Sample),
dereference_return=True,
require_return=True)
_Sound_NewSampleFromMem = _dll.private_function('Sound_NewSampleFromMem',
arg_types=[POINTER(c_ubyte), c_uint, c_char_p,
POINTER(Sound_AudioInfo), c_uint],
return_type=POINTER(Sound_Sample),
dereference_return=True,
require_return=True,
since=(9,9,9)) # Appears in header only
def Sound_NewSampleFromMem(data, ext, desired, bufferSize):
'''Start decoding a new sound sample from a buffer.
This is identical to `Sound_NewSample`, but it creates an `SDL_RWops`
for you from the buffer.
:Parameters:
`data` : `SDL_array` or sequence
Buffer holding encoded byte sound data
`ext` : str
File extension normally associated with a data format. Can
usually be None.
`desired` : `Sound_AudioInfo`
Format to convert sound data into. Can usually be None if you
don't need conversion.
`bufferSize` : int
Size, in bytes, to allocate for the decoding buffer
:rtype: `Sound_Sample`
:since: Not yet released in SDL_sound
'''
ref, data = SDL.array.to_ctypes(data, len(data), c_ubyte)
return _Sound_NewSampleFromMem(data, len(data), ext, desired, bufferSize)
Sound_NewSampleFromFile = _dll.function('Sound_NewSampleFromFile',
'''Start decoding a new sound sample from a file on disk.
This is identical to `Sound_NewSample`, but it creates an `SDL_RWops
for you from the file located at `filename`.
''',
args=['filename', 'desired', 'bufferSize'],
arg_types=[c_char_p, POINTER(Sound_AudioInfo), c_uint],
return_type=POINTER(Sound_Sample),
dereference_return=True,
require_return=True)
Sound_FreeSample = _dll.function('Sound_FreeSample',
'''Dispose of a `Sound_Sample`.
This will also close/dispose of the `SDL_RWops` that was used at
creation time. The `Sound_Sample` structure is invalid after this
call.
:Parameters:
`sample` : `Sound_Sample`
The sound sample to delete.
''',
args=['sample'],
arg_types=[POINTER(Sound_Sample)],
return_type=None)
Sound_GetDuration = _dll.function('Sound_GetDuration',
'''Retrieve the total play time of a sample, in milliseconds.
Report total time length of sample, in milliseconds. This is a fast
call. Duration is calculated during `Sound_NewSample`, so this is just
an accessor into otherwise opaque data.
Note that not all formats can determine a total time, some can't
be exact without fully decoding the data, and thus will estimate the
duration. Many decoders will require the ability to seek in the data
stream to calculate this, so even if we can tell you how long an .ogg
file will be, the same data set may fail if it's, say, streamed over an
HTTP connection.
:Parameters:
`sample` : `Sound_Sample`
Sample from which to retrieve duration information.
:rtype: int
:return: Sample length in milliseconds, or -1 if duration can't be
determined.
:since: Not yet released in SDL_sound
''',
args=['sample'],
arg_types=[POINTER(Sound_Sample)],
return_type=c_int,
since=(9,9,9))
Sound_SetBufferSize = _dll.function('Sound_SetBufferSize',
'''Change the current buffer size for a sample.
If the buffer size could be changed, then the ``sample.buffer`` and
``sample.buffer_size`` fields will reflect that. If they could not be
changed, then your original sample state is preserved. If the buffer is
shrinking, the data at the end of buffer is truncated. If the buffer is
growing, the contents of the new space at the end is undefined until you
decode more into it or initialize it yourself.
The buffer size specified must be a multiple of the size of a single
sample point. So, if you want 16-bit, stereo samples, then your sample
point size is (2 channels 16 bits), or 32 bits per sample, which is four
bytes. In such a case, you could specify 128 or 132 bytes for a buffer,
but not 129, 130, or 131 (although in reality, you'll want to specify a
MUCH larger buffer).
:Parameters:
`sample` : `Sound_Sample`
Sample to modify
`new_size` : int
The desired size, in bytes of the new buffer
''',
args=['sample', 'new_size'],
arg_types=[POINTER(Sound_Sample), c_uint],
return_type=c_int,
error_return=0)
Sound_Decode = _dll.function('Sound_Decode',
'''Decode more of the sound data in a `Sound_Sample`.
It will decode at most sample->buffer_size bytes into ``sample.buffer``
in the desired format, and return the number of decoded bytes.
If ``sample.buffer_size`` bytes could not be decoded, then refer to
``sample.flags`` to determine if this was an end-of-stream or error
condition.
:Parameters:
`sample` : `Sound_Sample`
Do more decoding to this sample
:rtype: int
:return: number of bytes decoded into ``sample.buffer``
''',
args=['sample'],
arg_types=[POINTER(Sound_Sample)],
return_type=c_uint)
Sound_DecodeAll = _dll.function('Sound_DecodeAll',
'''Decode the remainder of the sound data in a `Sound_Sample`.
This will dynamically allocate memory for the entire remaining sample.
``sample.buffer_size`` and ``sample.buffer`` will be updated to reflect
the new buffer. Refer to ``sample.flags`` to determine if the
decoding finished due to an End-of-stream or error condition.
Be aware that sound data can take a large amount of memory, and that
this function may block for quite awhile while processing. Also note
that a streaming source (for example, from a SDL_RWops that is getting
fed from an Internet radio feed that doesn't end) may fill all available
memory before giving up...be sure to use this on finite sound sources
only.
When decoding the sample in its entirety, the work is done one buffer
at a time. That is, sound is decoded in ``sample.buffer_size`` blocks, and
appended to a continually-growing buffer until the decoding completes.
That means that this function will need enough RAM to hold
approximately ``sample.buffer_size`` bytes plus the complete decoded
sample at most. The larger your buffer size, the less overhead this
function needs, but beware the possibility of paging to disk. Best to
make this user-configurable if the sample isn't specific and small.
:Parameters:
`sample` : `Sound_Sample`
Do all decoding for this sample.
:rtype: int
:return: number of bytes decoded into ``sample.buffer``
''',
args=['sample'],
arg_types=[POINTER(Sound_Sample)],
return_type=c_uint)
Sound_Rewind = _dll.function('Sound_Rewind',
'''Rewind a sample to the start.
Restart a sample at the start of its waveform data, as if newly
created with `Sound_NewSample`. If successful, the next call to
`Sound_Decode` will give audio data from the earliest point in the
stream.
Beware that this function will fail if the SDL_RWops that feeds the
decoder can not be rewound via it's seek method, but this can
theoretically be avoided by wrapping it in some sort of buffering
SDL_RWops.
This function will raise an exception if the RWops is not seekable, or
SDL_sound is not initialized.
If this function fails, the state of the sample is undefined, but it
is still safe to call `Sound_FreeSample` to dispose of it.
:Parameters:
`sample` : `Sound_Sample`
The sample to rewind
''',
args=['sample'],
arg_types=[POINTER(Sound_Sample)],
return_type=c_int,
error_return=0)
Sound_Seek = _dll.function('Sound_Seek',
'''Seek to a different point in a sample.
Reposition a sample's stream. If successful, the next call to
`Sound_Decode` or `Sound_DecodeAll` will give audio data from the
offset you specified.
The offset is specified in milliseconds from the start of the
sample.
Beware that this function can fail for several reasons. If the
SDL_RWops that feeds the decoder can not seek, this call will almost
certainly fail, but this can theoretically be avoided by wrapping it
in some sort of buffering SDL_RWops. Some decoders can never seek,
others can only seek with certain files. The decoders will set a flag
in the sample at creation time to help you determine this.
You should check ``sample.flags & SOUND_SAMPLEFLAG_CANSEEK``
before attempting. `Sound_Seek` reports failure immediately if this
flag isn't set. This function can still fail for other reasons if the
flag is set.
This function can be emulated in the application with `Sound_Rewind`
and predecoding a specific amount of the sample, but this can be
extremely inefficient. `Sound_Seek()` accelerates the seek on a
with decoder-specific code.
If this function fails, the sample should continue to function as if
this call was never made. If there was an unrecoverable error,
``sample.flags & SOUND_SAMPLEFLAG_ERROR`` will be set, which your
regular decoding loop can pick up.
On success, ERROR, EOF, and EAGAIN are cleared from sample->flags.
:Parameters:
`sample` : `Sound_Sample`
The sample to seek
`ms` : int
The new position, in milliseconds, from the start of sample
''',
args=['sample', 'ms'],
arg_types=[POINTER(Sound_Sample), c_uint],
return_type=c_int,
error_return=0)
| Python |
#!/usr/bin/env python
'''Functions related to the SDL shared library version.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
import dll
class SDL_version(Structure):
'''Version structure.
:Ivariables:
`major` : int
Major version number
`minor` : int
Minor version number
`patch` : int
Patch revision number
'''
_fields_ = [('major', c_ubyte),
('minor', c_ubyte),
('patch', c_ubyte)]
def __repr__(self):
return '%d.%d.%d' % \
(self.major, self.minor, self.patch)
def is_since(self, required):
if hasattr(required, 'major'):
return self.major >= required.major and \
self.minor >= required.minor and \
self.patch >= required.patch
else:
return self.major >= required[0] and \
self.minor >= required[1] and \
self.patch >= required[2]
def SDL_VERSIONNUM(major, minor, patch):
'''Turn the version numbers into a numeric value.
For example::
>>> SDL_VERSIONNUM(1, 2, 3)
1203
:Parameters:
- `major`: int
- `minor`: int
- `patch`: int
:rtype: int
'''
return x * 1000 + y * 100 + z
SDL_Linked_Version = dll.function('SDL_Linked_Version',
'''Get the version of the dynamically linked SDL library.
:rtype: `SDL_version`
''',
args=[],
arg_types=[],
return_type=POINTER(SDL_version),
dereference_return=True,
require_return=True)
def SDL_VERSION_ATLEAST(major, minor, patch):
'''Determine if the SDL library is at least the given version.
:Parameters:
- `major`: int
- `minor`: int
- `patch`: int
:rtype: bool
'''
v = SDL_Linked_Version()
return SDL_VERSIONNUM(v.major, v.minor, v.patch) >= \
SDL_VERSIONNUM(major, minor, patch)
# SDL_VERSION and SDL_COMPILEDVERSION not implemented as there is no
# sensible mapping to compiled version numbers.
| Python |
#!/usr/bin/env python
'''Darwin (OS X) support.
Appropriated from pygame.macosx
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import os
import sys
# SDL-ctypes on OS X requires PyObjC
from Foundation import *
from AppKit import *
import objc
import MacOS
import cocos.audio.SDL.dll
import cocos.audio.SDL.events
SDL = cocos.audio.SDL
__all__ = ['init']
# Need to do this if not running with a nib
def setupAppleMenu(app):
appleMenuController = NSAppleMenuController.alloc().init()
appleMenuController.retain()
appleMenu = NSMenu.alloc().initWithTitle_('')
appleMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('', None, '')
appleMenuItem.setSubmenu_(appleMenu)
app.mainMenu().addItem_(appleMenuItem)
appleMenuController.controlMenu_(appleMenu)
app.mainMenu().removeItem_(appleMenuItem)
# Need to do this if not running with a nib
def setupWindowMenu(app):
windowMenu = NSMenu.alloc().initWithTitle_('Window')
windowMenu.retain()
menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Minimize', 'performMiniaturize:', 'm')
windowMenu.addItem_(menuItem)
windowMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Window', None, '')
windowMenuItem.setSubmenu_(windowMenu)
app.mainMenu().addItem_(windowMenuItem)
app.setWindowsMenu_(windowMenu)
# Used to cleanly terminate
class SDLAppDelegate(NSObject):
def applicationShouldTerminate_(self, app):
event = SDL.events.SDL_Event()
event.type = SDL_QUIT
SDL.events.SDL_PushEvent(event)
return NSTerminateLater
def windowUpdateNotification_(self, notification):
win = notification.object()
if not SDL.dll.version_compatible((1, 2, 8)) and isinstance(win, objc.lookUpClass('SDL_QuartzWindow')):
# Seems to be a retain count bug in SDL.. workaround!
win.retain()
NSNotificationCenter.defaultCenter().removeObserver_name_object_(
self, NSWindowDidUpdateNotification, None)
self.release()
def setIcon(app, icon_data):
data = NSData.dataWithBytes_length_(icon_data, len(icon_data))
if data is None:
return
img = NSImage.alloc().initWithData_(data)
if img is None:
return
app.setApplicationIconImage_(img)
def install():
app = NSApplication.sharedApplication()
appDelegate = SDLAppDelegate.alloc().init()
app.setDelegate_(appDelegate)
appDelegate.retain()
NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
appDelegate,
'windowUpdateNotification:',
NSWindowDidUpdateNotification,
None)
if not app.mainMenu():
mainMenu = NSMenu.alloc().init()
app.setMainMenu_(mainMenu)
setupAppleMenu(app)
setupWindowMenu(app)
app.finishLaunching()
app.updateWindows()
app.activateIgnoringOtherApps_(True)
def S(*args):
return ''.join(args)
OSErr = objc._C_SHT
OUTPSN = 'o^{ProcessSerialNumber=LL}'
INPSN = 'n^{ProcessSerialNumber=LL}'
FUNCTIONS=[
# These two are public API
( u'GetCurrentProcess', S(OSErr, OUTPSN) ),
( u'SetFrontProcess', S(OSErr, INPSN) ),
# This is undocumented SPI
( u'CPSSetProcessName', S(OSErr, INPSN, objc._C_CHARPTR) ),
( u'CPSEnableForegroundOperation', S(OSErr, INPSN) ),
]
def WMEnable(name=None):
if name is None:
name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
if isinstance(name, unicode):
name = name.encode('utf-8')
if not hasattr(objc, 'loadBundleFunctions'):
return False
bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/ApplicationServices.framework'))
if bndl is None:
print >>sys.stderr, 'ApplicationServices missing'
return False
d = {}
app = NSApplication.sharedApplication()
objc.loadBundleFunctions(bndl, d, FUNCTIONS)
for (fn, sig) in FUNCTIONS:
if fn not in d:
print >>sys.stderr, 'Missing', fn
return False
err, psn = d['GetCurrentProcess']()
if err:
print >>sys.stderr, 'GetCurrentProcess', (err, psn)
return False
err = d['CPSSetProcessName'](psn, name)
if err:
print >>sys.stderr, 'CPSSetProcessName', (err, psn)
return False
err = d['CPSEnableForegroundOperation'](psn)
if err:
print >>sys.stderr, 'CPSEnableForegroundOperation', (err, psn)
return False
err = d['SetFrontProcess'](psn)
if err:
print >>sys.stderr, 'SetFrontProcess', (err, psn)
return False
return True
def init():
if not (MacOS.WMAvailable() or WMEnable()):
raise ImportError, "Can not access the window manager. Use py2app or execute with the pythonw script."
if not NSApp():
# running outside of a bundle
install()
# running inside a bundle, change dir
if (os.getcwd() == '/') and len(sys.argv) > 1:
os.chdir(os.path.dirname(sys.argv[0]))
return True
| Python |
#!/usr/bin/env python
'''Constants and enums for all SDL submodules.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import sys
# enum SDLKey {
# The keyboard syms have been cleverly chosen to map to ASCII
SDLK_UNKNOWN = 0
SDLK_FIRST = 0
SDLK_BACKSPACE = 8
SDLK_TAB = 9
SDLK_CLEAR = 12
SDLK_RETURN = 13
SDLK_PAUSE = 19
SDLK_ESCAPE = 27
SDLK_SPACE = 32
SDLK_EXCLAIM = 33
SDLK_QUOTEDBL = 34
SDLK_HASH = 35
SDLK_DOLLAR = 36
SDLK_AMPERSAND = 38
SDLK_QUOTE = 39
SDLK_LEFTPAREN = 40
SDLK_RIGHTPAREN = 41
SDLK_ASTERISK = 42
SDLK_PLUS = 43
SDLK_COMMA = 44
SDLK_MINUS = 45
SDLK_PERIOD = 46
SDLK_SLASH = 47
SDLK_0 = 48
SDLK_1 = 49
SDLK_2 = 50
SDLK_3 = 51
SDLK_4 = 52
SDLK_5 = 53
SDLK_6 = 54
SDLK_7 = 55
SDLK_8 = 56
SDLK_9 = 57
SDLK_COLON = 58
SDLK_SEMICOLON = 59
SDLK_LESS = 60
SDLK_EQUALS = 61
SDLK_GREATER = 62
SDLK_QUESTION = 63
SDLK_AT = 64
# Skip uppercase letters
SDLK_LEFTBRACKET = 91
SDLK_BACKSLASH = 92
SDLK_RIGHTBRACKET = 93
SDLK_CARET = 94
SDLK_UNDERSCORE = 95
SDLK_BACKQUOTE = 96
SDLK_a = 97
SDLK_b = 98
SDLK_c = 99
SDLK_d = 100
SDLK_e = 101
SDLK_f = 102
SDLK_g = 103
SDLK_h = 104
SDLK_i = 105
SDLK_j = 106
SDLK_k = 107
SDLK_l = 108
SDLK_m = 109
SDLK_n = 110
SDLK_o = 111
SDLK_p = 112
SDLK_q = 113
SDLK_r = 114
SDLK_s = 115
SDLK_t = 116
SDLK_u = 117
SDLK_v = 118
SDLK_w = 119
SDLK_x = 120
SDLK_y = 121
SDLK_z = 122
SDLK_DELETE = 127
# End of ASCII mapped keysyms
# International keyboard syms
SDLK_WORLD_0 = 160 # 0xA0
SDLK_WORLD_1 = 161
SDLK_WORLD_2 = 162
SDLK_WORLD_3 = 163
SDLK_WORLD_4 = 164
SDLK_WORLD_5 = 165
SDLK_WORLD_6 = 166
SDLK_WORLD_7 = 167
SDLK_WORLD_8 = 168
SDLK_WORLD_9 = 169
SDLK_WORLD_10 = 170
SDLK_WORLD_11 = 171
SDLK_WORLD_12 = 172
SDLK_WORLD_13 = 173
SDLK_WORLD_14 = 174
SDLK_WORLD_15 = 175
SDLK_WORLD_16 = 176
SDLK_WORLD_17 = 177
SDLK_WORLD_18 = 178
SDLK_WORLD_19 = 179
SDLK_WORLD_20 = 180
SDLK_WORLD_21 = 181
SDLK_WORLD_22 = 182
SDLK_WORLD_23 = 183
SDLK_WORLD_24 = 184
SDLK_WORLD_25 = 185
SDLK_WORLD_26 = 186
SDLK_WORLD_27 = 187
SDLK_WORLD_28 = 188
SDLK_WORLD_29 = 189
SDLK_WORLD_30 = 190
SDLK_WORLD_31 = 191
SDLK_WORLD_32 = 192
SDLK_WORLD_33 = 193
SDLK_WORLD_34 = 194
SDLK_WORLD_35 = 195
SDLK_WORLD_36 = 196
SDLK_WORLD_37 = 197
SDLK_WORLD_38 = 198
SDLK_WORLD_39 = 199
SDLK_WORLD_40 = 200
SDLK_WORLD_41 = 201
SDLK_WORLD_42 = 202
SDLK_WORLD_43 = 203
SDLK_WORLD_44 = 204
SDLK_WORLD_45 = 205
SDLK_WORLD_46 = 206
SDLK_WORLD_47 = 207
SDLK_WORLD_48 = 208
SDLK_WORLD_49 = 209
SDLK_WORLD_50 = 210
SDLK_WORLD_51 = 211
SDLK_WORLD_52 = 212
SDLK_WORLD_53 = 213
SDLK_WORLD_54 = 214
SDLK_WORLD_55 = 215
SDLK_WORLD_56 = 216
SDLK_WORLD_57 = 217
SDLK_WORLD_58 = 218
SDLK_WORLD_59 = 219
SDLK_WORLD_60 = 220
SDLK_WORLD_61 = 221
SDLK_WORLD_62 = 222
SDLK_WORLD_63 = 223
SDLK_WORLD_64 = 224
SDLK_WORLD_65 = 225
SDLK_WORLD_66 = 226
SDLK_WORLD_67 = 227
SDLK_WORLD_68 = 228
SDLK_WORLD_69 = 229
SDLK_WORLD_70 = 230
SDLK_WORLD_71 = 231
SDLK_WORLD_72 = 232
SDLK_WORLD_73 = 233
SDLK_WORLD_74 = 234
SDLK_WORLD_75 = 235
SDLK_WORLD_76 = 236
SDLK_WORLD_77 = 237
SDLK_WORLD_78 = 238
SDLK_WORLD_79 = 239
SDLK_WORLD_80 = 240
SDLK_WORLD_81 = 241
SDLK_WORLD_82 = 242
SDLK_WORLD_83 = 243
SDLK_WORLD_84 = 244
SDLK_WORLD_85 = 245
SDLK_WORLD_86 = 246
SDLK_WORLD_87 = 247
SDLK_WORLD_88 = 248
SDLK_WORLD_89 = 249
SDLK_WORLD_90 = 250
SDLK_WORLD_91 = 251
SDLK_WORLD_92 = 252
SDLK_WORLD_93 = 253
SDLK_WORLD_94 = 254
SDLK_WORLD_95 = 255 # 0xFF
# Numeric keypad
SDLK_KP0 = 256
SDLK_KP1 = 257
SDLK_KP2 = 258
SDLK_KP3 = 259
SDLK_KP4 = 260
SDLK_KP5 = 261
SDLK_KP6 = 262
SDLK_KP7 = 263
SDLK_KP8 = 264
SDLK_KP9 = 265
SDLK_KP_PERIOD = 266
SDLK_KP_DIVIDE = 267
SDLK_KP_MULTIPLY = 268
SDLK_KP_MINUS = 269
SDLK_KP_PLUS = 270
SDLK_KP_ENTER = 271
SDLK_KP_EQUALS = 272
# Arrows + Home/End pad
SDLK_UP = 273
SDLK_DOWN = 274
SDLK_RIGHT = 275
SDLK_LEFT = 276
SDLK_INSERT = 277
SDLK_HOME = 278
SDLK_END = 279
SDLK_PAGEUP = 280
SDLK_PAGEDOWN = 281
# Function keys
SDLK_F1 = 282
SDLK_F2 = 283
SDLK_F3 = 284
SDLK_F4 = 285
SDLK_F5 = 286
SDLK_F6 = 287
SDLK_F7 = 288
SDLK_F8 = 289
SDLK_F9 = 290
SDLK_F10 = 291
SDLK_F11 = 292
SDLK_F12 = 293
SDLK_F13 = 294
SDLK_F14 = 295
SDLK_F15 = 296
# Key state modifier keys
SDLK_NUMLOCK = 300
SDLK_CAPSLOCK = 301
SDLK_SCROLLOCK = 302
SDLK_RSHIFT = 303
SDLK_LSHIFT = 304
SDLK_RCTRL = 305
SDLK_LCTRL = 306
SDLK_RALT = 307
SDLK_LALT = 308
SDLK_RMETA = 309
SDLK_LMETA = 310
SDLK_LSUPER = 311 # Left "Windows" key
SDLK_RSUPER = 312 # Right "Windows" key
SDLK_MODE = 313 # "Alt Gr" key
SDLK_COMPOSE = 314 # Multi-key compose key
# Miscellaneous function keys
SDLK_HELP = 315
SDLK_PRINT = 316
SDLK_SYSREQ = 317
SDLK_BREAK = 318
SDLK_MENU = 319
SDLK_POWER = 320 # Power Macintosh power key
SDLK_EURO = 321 # Some european keyboards
SDLK_UNDO = 322 # Atari keyboard has Undo
SDLK_LAST = 323 # Keep me updated please.
# end of enum SDLKey
# enum SDLMod
KMOD_NONE = 0x0000
KMOD_LSHIFT = 0x0001
KMOD_RSHIFT = 0x0002
KMOD_LCTRL = 0x0040
KMOD_RCTRL = 0x0080
KMOD_LALT = 0x0100
KMOD_RALT = 0x0200
KMOD_LMETA = 0x0400
KMOD_RMETA = 0x0800
KMOD_NUM = 0x1000
KMOD_CAPS = 0x2000
KMOD_MODE = 0x4000
KMOD_RESERVED = 0x8000
# end of enum SDLMod
KMOD_CTRL = KMOD_LCTRL | KMOD_RCTRL
KMOD_SHIFT = KMOD_LSHIFT | KMOD_RSHIFT
KMOD_ALT = KMOD_LALT | KMOD_RALT
KMOD_META = KMOD_LMETA | KMOD_RMETA
#BEGIN GENERATED CONSTANTS; see support/make_constants.py
#Constants from SDL_mouse.h:
SDL_BUTTON_LEFT = 0x00000001
SDL_BUTTON_MIDDLE = 0x00000002
SDL_BUTTON_RIGHT = 0x00000003
SDL_BUTTON_WHEELUP = 0x00000004
SDL_BUTTON_WHEELDOWN = 0x00000005
#Constants from SDL_version.h:
SDL_MAJOR_VERSION = 0x00000001
SDL_MINOR_VERSION = 0x00000002
SDL_PATCHLEVEL = 0x0000000a
#Constants from SDL.h:
SDL_INIT_TIMER = 0x00000001
SDL_INIT_AUDIO = 0x00000010
SDL_INIT_VIDEO = 0x00000020
SDL_INIT_CDROM = 0x00000100
SDL_INIT_JOYSTICK = 0x00000200
SDL_INIT_NOPARACHUTE = 0x00100000
SDL_INIT_EVENTTHREAD = 0x01000000
SDL_INIT_EVERYTHING = 0x0000ffff
#Constants from SDL_mutex.h:
SDL_MUTEX_TIMEDOUT = 0x00000001
#Constants from SDL_video.h:
SDL_ALPHA_OPAQUE = 0x000000ff
SDL_ALPHA_TRANSPARENT = 0x00000000
SDL_SWSURFACE = 0x00000000
SDL_HWSURFACE = 0x00000001
SDL_ASYNCBLIT = 0x00000004
SDL_ANYFORMAT = 0x10000000
SDL_HWPALETTE = 0x20000000
SDL_DOUBLEBUF = 0x40000000
SDL_FULLSCREEN = 0x80000000
SDL_OPENGL = 0x00000002
SDL_OPENGLBLIT = 0x0000000a
SDL_RESIZABLE = 0x00000010
SDL_NOFRAME = 0x00000020
SDL_HWACCEL = 0x00000100
SDL_SRCCOLORKEY = 0x00001000
SDL_RLEACCELOK = 0x00002000
SDL_RLEACCEL = 0x00004000
SDL_SRCALPHA = 0x00010000
SDL_PREALLOC = 0x01000000
SDL_YV12_OVERLAY = 0x32315659
SDL_IYUV_OVERLAY = 0x56555949
SDL_YUY2_OVERLAY = 0x32595559
SDL_UYVY_OVERLAY = 0x59565955
SDL_YVYU_OVERLAY = 0x55595659
SDL_LOGPAL = 0x00000001
SDL_PHYSPAL = 0x00000002
#Constants from SDL_name.h:
NeedFunctionPrototypes = 0x00000001
#Constants from SDL_endian.h:
SDL_LIL_ENDIAN = 0x000004d2
SDL_BIG_ENDIAN = 0x000010e1
#Constants from SDL_audio.h:
AUDIO_U8 = 0x00000008
AUDIO_S8 = 0x00008008
AUDIO_U16LSB = 0x00000010
AUDIO_S16LSB = 0x00008010
AUDIO_U16MSB = 0x00001010
AUDIO_S16MSB = 0x00009010
SDL_MIX_MAXVOLUME = 0x00000080
#Constants from begin_code.h:
NULL = 0x00000000
#Constants from SDL_cdrom.h:
SDL_MAX_TRACKS = 0x00000063
SDL_AUDIO_TRACK = 0x00000000
SDL_DATA_TRACK = 0x00000004
CD_FPS = 0x0000004b
#Constants from SDL_events.h:
SDL_RELEASED = 0x00000000
SDL_PRESSED = 0x00000001
SDL_ALLEVENTS = 0xffffffff
SDL_IGNORE = 0x00000000
SDL_DISABLE = 0x00000000
SDL_ENABLE = 0x00000001
#Constants from SDL_active.h:
SDL_APPMOUSEFOCUS = 0x00000001
SDL_APPINPUTFOCUS = 0x00000002
SDL_APPACTIVE = 0x00000004
#Constants from SDL_joystick.h:
SDL_HAT_CENTERED = 0x00000000
SDL_HAT_UP = 0x00000001
SDL_HAT_RIGHT = 0x00000002
SDL_HAT_DOWN = 0x00000004
SDL_HAT_LEFT = 0x00000008
#Constants from SDL_keyboard.h:
SDL_ALL_HOTKEYS = 0xffffffff
SDL_DEFAULT_REPEAT_DELAY = 0x000001f4
SDL_DEFAULT_REPEAT_INTERVAL = 0x0000001e
#Constants from SDL_rwops.h:
RW_SEEK_SET = 0x00000000
RW_SEEK_CUR = 0x00000001
RW_SEEK_END = 0x00000002
#Constants from SDL_timer.h:
SDL_TIMESLICE = 0x0000000a
TIMER_RESOLUTION = 0x0000000a
#END GENERATED CONSTANTS
# From SDL_audio.h (inserted manually)
# enum SDL_audiostatus
(SDL_AUDIO_STOPPED,
SDL_AUDIO_PLAYING,
SDL_AUDIO_PAUSED) = range(3)
if sys.byteorder == 'little':
AUDIO_U16SYS = AUDIO_U16LSB
AUDIO_S16SYS = AUDIO_S16LSB
else:
AUDIO_U16SYS = AUDIO_U16MSB
AUDIO_S16SYS = AUDIO_S16MSB
AUDIO_U16 = AUDIO_U16LSB
AUDIO_S16 = AUDIO_S16LSB
# From SDL_cdrom.h (inserted manually)
# enum CDstatus
(CD_TRAYEMPTY,
CD_STOPPED,
CD_PLAYING,
CD_PAUSED) = range(4)
CD_ERROR = -1
# From SDL_events.h (inserted manually)
# enum SDL_EventType
(SDL_NOEVENT,
SDL_ACTIVEEVENT,
SDL_KEYDOWN,
SDL_KEYUP,
SDL_MOUSEMOTION,
SDL_MOUSEBUTTONDOWN,
SDL_MOUSEBUTTONUP,
SDL_JOYAXISMOTION,
SDL_JOYBALLMOTION,
SDL_JOYHATMOTION,
SDL_JOYBUTTONDOWN,
SDL_JOYBUTTONUP,
SDL_QUIT,
SDL_SYSWMEVENT,
SDL_EVENT_RESERVEDA,
SDL_EVENT_RESERVEDB,
SDL_VIDEORESIZE,
SDL_VIDEOEXPOSE,
SDL_EVENT_RESERVED2,
SDL_EVENT_RESERVED3,
SDL_EVENT_RESERVED4,
SDL_EVENT_RESERVED5,
SDL_EVENT_RESERVED6,
SDL_EVENT_RESERVED7) = range(24)
SDL_USEREVENT = 24
SDL_NUMEVENTS = 32
def SDL_EVENTMASK(x):
'''Used for predefining event masks.'''
return 1 << x
# enum SDL_EventMask
SDL_ACTIVEEVENTMASK = SDL_EVENTMASK(SDL_ACTIVEEVENT)
SDL_KEYDOWNMASK = SDL_EVENTMASK(SDL_KEYDOWN)
SDL_KEYUPMASK = SDL_EVENTMASK(SDL_KEYUP)
SDL_KEYEVENTMASK = SDL_KEYUPMASK | \
SDL_KEYDOWNMASK
SDL_MOUSEMOTIONMASK = SDL_EVENTMASK(SDL_MOUSEMOTION)
SDL_MOUSEBUTTONDOWNMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN)
SDL_MOUSEBUTTONUPMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONUP)
SDL_MOUSEEVENTMASK = SDL_MOUSEMOTIONMASK | \
SDL_MOUSEBUTTONDOWNMASK | \
SDL_MOUSEBUTTONUPMASK
SDL_JOYAXISMOTIONMASK = SDL_EVENTMASK(SDL_JOYAXISMOTION)
SDL_JOYBALLMOTIONMASK = SDL_EVENTMASK(SDL_JOYBALLMOTION)
SDL_JOYHATMOTIONMASK = SDL_EVENTMASK(SDL_JOYHATMOTION)
SDL_JOYBUTTONDOWNMASK = SDL_EVENTMASK(SDL_JOYBUTTONDOWN)
SDL_JOYBUTTONUPMASK = SDL_EVENTMASK(SDL_JOYBUTTONUP)
SDL_JOYEVENTMASK = SDL_JOYAXISMOTIONMASK | \
SDL_JOYBALLMOTIONMASK | \
SDL_JOYHATMOTIONMASK | \
SDL_JOYBUTTONDOWNMASK | \
SDL_JOYBUTTONUPMASK
SDL_QUITMASK = SDL_EVENTMASK(SDL_QUIT)
SDL_SYSWMEVENTMASK = SDL_EVENTMASK(SDL_SYSWMEVENT)
SDL_VIDEORESIZEMASK = SDL_EVENTMASK(SDL_VIDEORESIZE)
SDL_VIDEOEXPOSEMASK = SDL_EVENTMASK(SDL_VIDEOEXPOSE)
# enum SDL_eventaction
(SDL_ADDEVENT,
SDL_PEEKEVENT,
SDL_GETEVENT) = range(3)
#From SDL_joystick.h (inserted manually)
SDL_HAT_RIGHTUP = SDL_HAT_RIGHT | SDL_HAT_UP
SDL_HAT_RIGHTDOWN = SDL_HAT_RIGHT | SDL_HAT_DOWN
SDL_HAT_LEFTUP = SDL_HAT_LEFT | SDL_HAT_UP
SDL_HAT_LEFTDOWN = SDL_HAT_LEFT | SDL_HAT_DOWN
# From SDL_video.h (inserted manually)
# enum SDL_GLattr
(SDL_GL_RED_SIZE,
SDL_GL_GREEN_SIZE,
SDL_GL_BLUE_SIZE,
SDL_GL_ALPHA_SIZE,
SDL_GL_BUFFER_SIZE,
SDL_GL_DOUBLEBUFFER,
SDL_GL_DEPTH_SIZE,
SDL_GL_STENCIL_SIZE,
SDL_GL_ACCUM_RED_SIZE,
SDL_GL_ACCUM_GREEN_SIZE,
SDL_GL_ACCUM_BLUE_SIZE,
SDL_GL_ACCUM_ALPHA_SIZE,
SDL_GL_STEREO,
SDL_GL_MULTISAMPLEBUFFERS,
SDL_GL_MULTISAMPLESAMPLES,
SDL_GL_ACCELERATED_VISUAL,
SDL_GL_SWAP_CONTROL) = range(17)
# enum SDL_GrabMode
(SDL_GRAB_QUERY,
SDL_GRAB_OFF,
SDL_GRAB_ON) = range(-1,2)
# From SDL_ttf.h (inserted manually)
TTF_STYLE_NORMAL = 0x00
TTF_STYLE_BOLD = 0x01
TTF_STYLE_ITALIC = 0x02
TTF_STYLE_UNDERLINE = 0x04
# From SDL_mixer.h (inserted manually)
MIX_CHANNELS = 8
MIX_DEFAULT_FREQUENCY = 22050
MIX_MAX_VOLUME = 128
MIX_CHANNEL_POST = -2
MIX_EFFECTSMAXSPEED = 'MIX_EFFECTSMAXSPEED'
MIX_DEFAULT_CHANNELS = 2
if sys.byteorder == 'little':
MIX_DEFAULT_FORMAT = AUDIO_S16LSB
else:
MIX_DEFAULT_FORMAT = AUDIO_S16MSB
# enum Mix_Fading
(MIX_NO_FADING,
MIX_FADING_OUT,
MIX_FADING_IN) = range(3)
# enum Mix_MusicType
(MUS_NONE,
MUS_CMD,
MUS_WAV,
MUS_MOD,
MUS_MID,
MUS_OGG,
MUS_MP3) = range(7)
# From SDL_sound.h (inserted manually):
# enum Sound_SampleFlags
SOUND_SAMPLEFLAG_NONE = 0
SOUND_SAMPLEFLAG_CANSEEK = 1
SOUND_SAMPLEFLAG_EOF = 1 << 29
SOUND_SAMPLEFLAG_ERROR = 1 << 30
SOUND_SAMPLEFLAG_EGAIN = 1 << 31
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
from ctypes.util import find_library
import sys
# Private version checking declared before SDL.version can be
# imported.
class _SDL_version(Structure):
_fields_ = [('major', c_ubyte),
('minor', c_ubyte),
('patch', c_ubyte)]
def __repr__(self):
return '%d.%d.%d' % \
(self.major, self.minor, self.patch)
def _version_parts(v):
'''Return a tuple (major, minor, patch) for `v`, which can be
an _SDL_version, string or tuple.'''
if hasattr(v, 'major') and hasattr(v, 'minor') and hasattr(v, 'patch'):
return v.major, v.minor, v.patch
elif type(v) == tuple:
return v
elif type(v) == str:
return tuple([int(i) for i in v.split('.')])
else:
raise TypeError
def _version_string(v):
return '%d.%d.%d' % _version_parts(v)
def _platform_library_name(library):
if sys.platform[:5] == 'linux':
return 'lib%s.so' % library
elif sys.platform == 'darwin':
return '%s.framework' % library
elif sys.platform == 'win32':
return '%s.dll' % library
return library
class SDL_DLL:
def __init__(self, library_name, version_function_name, version=None):
self.library_name = library_name
if sys.platform=='win32':
try:
self._load_library_win()
except WindowsError:
raise ImportError, ('Dynamic library "%s" was not found' %
library_name)
else:
self._load_library_nix(version)
# Get the version of the DLL we're using
if version_function_name:
try:
version_function = getattr(self._dll, version_function_name)
version_function.restype = POINTER(_SDL_version)
self._version = _version_parts(version_function().contents)
except AttributeError:
self._version = (0, 0, 0)
else:
self._version = (0, 0, 0)
def _load_library_win(self):
'''
loads library from the dir cocos.sdl_lib_path
Normally it is the path to the pygame package.
If set to None will look first in the current working directory,
then in system32; that can be handy when using py2exe
'''
import os
import cocos
# we must change cwd because some .dll s will directly load other dlls
old_cwd = os.getcwd()
if cocos.sdl_lib_path is not None:
os.chdir(cocos.sdl_lib_path)
try:
self._dll = getattr(cdll, self.library_name)
finally:
os.chdir(old_cwd)
def _load_library_nix(self, version):
library = find_library(self.library_name)
if library is None and version is not None:
# try to lookup with version. this is useful in linux, sometimes
# there is'nt a libSDL.so but a libSDL-1.2.so
library = find_library("%s-%s" % (self.library_name, version))
if not library:
raise ImportError, 'Dynamic library "%s" was not found' % \
_platform_library_name(self.library_name)
self._dll = getattr(cdll, library)
def version_compatible(self, v):
'''Returns True iff `v` is equal to or later than the loaded library
version.'''
v = _version_parts(v)
for i in range(3):
if self._version[i] < v[i]:
return False
return True
def assert_version_compatible(self, name, since):
'''Raises an exception if `since` is later than the loaded library.'''
if not version_compatible(since):
import cocos.audio.SDL.error
raise cocos.audio.SDL.error.SDL_NotImplementedError, \
'%s requires SDL version %s; currently using version %s' % \
(name, _version_string(since), _version_string(self._version))
def private_function(self, name, **kwargs):
'''Construct a wrapper function for ctypes with internal documentation
and no argument names.'''
kwargs['doc'] = 'Private wrapper for %s' % name
kwargs['args'] = []
return self.function(name, **kwargs)
def function(self, name, doc, args=[], arg_types=[],
return_type=None,
dereference_return=False,
require_return=False,
success_return=None,
error_return=None,
since=None):
'''Construct a wrapper function for ctypes.
:Parameters:
`name`
The name of the function as it appears in the shared library.
`doc`
Docstring to associate with the wrapper function.
`args`
List of strings giving the argument names.
`arg_types`
List of ctypes classes giving the argument types.
`return_type`
The ctypes class giving the wrapped function's native
return type.
`dereference_return`
If True, the return value is assumed to be a pointer and
will be dereferenced via ``.contents`` before being
returned to the user application.
`require_return`
Used in conjunction with `dereference_return`; if True, an
exception will be raised if the result is NULL; if False
None will be returned when the result is NULL.
`success_return`
If not None, the expected result of the wrapped function.
If the return value does not equal success_return, an
exception will be raised.
`error_return`
If not None, the error result of the wrapped function. If
the return value equals error_return, an exception will be
raised. Cannot be used in conjunction with
`success_return`.
`since`
Tuple (major, minor, patch) or string 'x.y.z' of the first
version of SDL in which this function appears. If the
loaded version predates it, a placeholder function that
raises `SDL_NotImplementedError` will be returned instead.
Set to None if the function is in all versions of SDL.
'''
# Check for version compatibility first
if since and not self.version_compatible(since):
def _f(*args, **kwargs):
import cocos.audio.SDL.error
raise cocos.audio.SDL.error.SDL_NotImplementedError, \
'%s requires %s %s; currently using version %s' % \
(name, self.library_name, _version_string(since),
_version_string(self._version))
if args:
_f._args = args
_f.__doc__ = doc
try:
_f.func_name = name
except TypeError: # read-only in Python 2.3
pass
return _f
# Ok, get function from ctypes
func = getattr(self._dll, name)
func.argtypes = arg_types
func.restype = return_type
if dereference_return:
if require_return:
# Construct a function which dereferences the pointer result,
# or raises an exception if NULL is returned.
def _f(*args, **kwargs):
result = func(*args, **kwargs)
if result:
return result.contents
import cocos.audio.SDL.error
raise cocos.audio.SDL.error.SDL_Exception, cocos.audio.SDL.error.SDL_GetError()
else:
# Construct a function which dereferences the pointer result,
# or returns None if NULL is returned.
def _f(*args, **kwargs):
result = func(*args, **kwargs)
if result:
return result.contents
return None
elif success_return is not None:
# Construct a function which returns None, but raises an exception
# if the C function returns a failure code.
def _f(*args, **kwargs):
result = func(*args, **kwargs)
if result != success_return:
import cocos.audio.SDL.error
raise cocos.audio.SDL.error.SDL_Exception, cocos.audio.SDL.error.SDL_GetError()
return result
elif error_return is not None:
# Construct a function which returns None, but raises an exception
# if the C function returns a failure code.
def _f(*args, **kwargs):
result = func(*args, **kwargs)
if result == error_return:
import cocos.audio.SDL.error
raise cocos.audio.SDL.error.SDL_Exception, cocus.audio.SDL.error.SDL_GetError()
return result
elif require_return:
# Construct a function which returns the usual result, or returns
# None if NULL is returned.
def _f(*args, **kwargs):
result = func(*args, **kwargs)
if not result:
import cocos.audio.SDL.error
raise cocos.audio.SDL.error.SDL_Exception, cocos.audio.SDL.error.SDL_GetError()
return result
else:
# Construct a function which returns the C function's return
# value.
def _f(*args, **kwargs):
return func(*args, **kwargs)
if args:
_f._args = args
_f.__doc__ = doc
try:
_f.func_name = name
except TypeError: # read-only in Python 2.3
pass
return _f
# Shortcuts to the SDL core library
_dll = SDL_DLL('SDL', 'SDL_Linked_Version', '1.2')
version_compatible = _dll.version_compatible
assert_version_compatible = _dll.assert_version_compatible
private_function = _dll.private_function
function = _dll.function
| Python |
#!/usr/bin/env python
'''A simple multi-channel audio mixer.
It supports 8 channels of 16 bit stereo audio, plus a single channel
of music, mixed by MidMod MOD, Timidity MIDI or SMPEG MP3 libraries.
The mixer can currently load Microsoft WAVE files and Creative Labs VOC
files as audio samples, and can load MIDI files via Timidity and the
following music formats via MikMod: MOD, S3M, IT, XM. It can load Ogg
Vorbis streams as music if built with the Ogg Vorbis libraries, and finally
it can load MP3 music using the SMPEG library.
The process of mixing MIDI files to wave output is very CPU intensive, so
if playing regular WAVE files sounds great, but playing MIDI files sounds
choppy, try using 8-bit audio, mono audio, or lower frequencies.
:note: The music stream does not resample to the required audio rate. You
must call `Mix_OpenAudio` with the sampling rate of your music track.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
import dll
import version
import array
import rwops
_dll = dll.SDL_DLL('SDL_mixer', 'Mix_Linked_Version', '1.2')
Mix_Linked_Version = _dll.function('Mix_Linked_Version',
'''Get the version of the dynamically linked SDL_mixer library.
''',
args=[],
arg_types=[],
return_type=POINTER(version.SDL_version),
dereference_return=True,
require_return=True)
class Mix_Chunk(Structure):
'''Internal format for an audio chunk.
:Ivariables:
`allocated` : int
Undocumented.
`abuf` : `SDL_array`
Buffer of audio data
`alen` : int
Length of audio buffer
`volume` : int
Per-sample volume, in range [0, 128]
'''
_fields_ = [('allocated', c_int),
('_abuf', POINTER(c_ubyte)),
('alen', c_uint),
('volume', c_ubyte)]
def __getattr__(self, attr):
if attr == 'abuf':
return array.SDL_array(self._abuf, self.alen, c_ubyte)
raise AttributeError, attr
# opaque type
_Mix_Music = c_void_p
Mix_OpenAudio = _dll.function('Mix_OpenAudio',
'''Open the mixer with a certain audio format.
:Parameters:
`frequency` : int
Samples per second. Typical values are 22050, 44100, 44800.
`format` : int
Audio format; one of AUDIO_U8, AUDIO_S8, AUDIO_U16LSB,
AUDIO_S16LSB, AUDIO_U16MSB or AUDIO_S16MSB
`channels` : int
Either 1 for monophonic or 2 for stereo.
`chunksize` : int
Size of the audio buffer. Typical values are 4096, 8192.
''',
args=['frequency', 'format', 'channels', 'chunksize'],
arg_types=[c_int, c_ushort, c_int, c_int],
return_type=c_int,
error_return=-1)
Mix_AllocateChannels = _dll.function('Mix_AllocateChannels',
'''Dynamically change the number of channels managed by the mixer.
If decreasing the number of channels, the upper channels
are stopped.
:Parameters:
- `numchans`: int
:rtype: int
:return: the new number of allocated channels.
''',
args=['numchans'],
arg_types=[c_int],
return_type=c_int)
_Mix_QuerySpec = _dll.private_function('Mix_QuerySpec',
arg_types=[POINTER(c_int), POINTER(c_ushort), POINTER(c_int)],
return_type=c_int)
def Mix_QuerySpec():
'''Find out what the actual audio device parameters are.
The function returns a tuple giving each parameter value. The first
value is 1 if the audio has been opened, 0 otherwise.
:rtype: (int, int, int, int)
:return: (opened, frequency, format, channels)
'''
frequency, format, channels = c_int(), c_ushort(), c_int()
opened = _Mix_QuerySpec(byref(frequency), byref(format), byref(channels))
return opened, frequency.value, format.value, channels.value
Mix_LoadWAV_RW = _dll.function('Mix_LoadWAV_RW',
'''Load a WAV, RIFF, AIFF, OGG or VOC file from a RWops source.
:rtype: `Mix_Chunk`
''',
args=['src', 'freesrc'],
arg_types=[POINTER(rwops.SDL_RWops), c_int],
return_type=POINTER(Mix_Chunk),
dereference_return=True,
require_return=True)
def Mix_LoadWAV(file):
'''Load a WAV, RIFF, AIFF, OGG or VOC file.
:Parameters:
`file` : string
Filename to load.
:rtype: `Mix_Chunk`
'''
return Mix_LoadWAV_RW(rwops.SDL_RWFromFile(file, 'rb'), 1)
Mix_LoadMUS = _dll.function('Mix_LoadMUS',
'''Load a WAV, MID, OGG, MP3 or MOD file.
:Parameters:
`file` : string
Filename to load.
:rtype: ``Mix_Music``
''',
args=['file'],
arg_types=[c_char_p],
return_type=_Mix_Music,
require_return=True)
Mix_LoadMUS_RW = _dll.function('Mix_LoadMUS_RW',
'''Load a MID, OGG, MP3 or MOD file from a RWops source.
:Parameters:
`src` : `SDL_RWops`
Readable RWops to load from.
`freesrc` : `int`
If non-zero, the source will be closed after loading.
:rtype: ``Mix_Music``
''',
args=['file'],
arg_types=[c_char_p],
return_type=_Mix_Music,
require_return=True)
_Mix_QuickLoad_WAV = _dll.private_function('Mix_QuickLoad_WAV',
arg_types=[POINTER(c_ubyte)],
return_type=POINTER(Mix_Chunk),
dereference_return=True,
require_return=True)
def Mix_QuickLoad_WAV(mem):
'''Load a wave file of the mixer format from a sequence or SDL_array.
:Parameters:
- `mem`: sequence or `SDL_array`
:rtype: `Mix_Chunk`
'''
ref, mem = array.to_ctypes(mem, len(mem), c_ubyte)
return _Mix_QuickLoad_WAV(mem)
_Mix_QuickLoad_RAW = _dll.private_function('Mix_QuickLoad_RAW',
arg_types=[POINTER(c_ubyte), c_uint],
return_type=POINTER(Mix_Chunk),
dereference_return=True,
require_return=True)
def Mix_QuickLoad_RAW(mem):
'''Load raw audio data of the mixer format from a sequence or SDL_array.
:Parameters:
- `mem`: sequence or `SDL_array`
:rtype: `Mix_Chunk`
'''
l = len(mem)
ref, mem = SDL.array.to_ctypes(mem, len(mem), c_ubyte)
return _Mix_QuickLoad_RAW(mem, l)
Mix_FreeChunk = _dll.function('Mix_FreeChunk',
'''Free an audio chunk previously loaded.
:Parameters:
- `chunk`: `Mix_Chunk`
''',
args=['chunk'],
arg_types=[POINTER(Mix_Chunk)],
return_type=None)
Mix_FreeMusic = _dll.function('Mix_FreeMusic',
'''Free a music chunk previously loaded.
:Parameters:
- `music`: ``Mix_Music``
''',
args=['music'],
arg_types=[_Mix_Music],
return_type=None)
Mix_GetMusicType = _dll.function('Mix_GetMusicType',
'''Get the music format of a mixer music.
Returns the format of the currently playing music if `music` is None.
:Parameters:
- `music`: ``Mix_Music``
:rtype: int
:return: one of `MUS_NONE`, `MUS_CMD`, `MUS_WAV`, `MUS_MOD`, `MUS_MID`,
`MUS_OGG` or `MUS_MP3`
''',
args=['music'],
arg_types=[_Mix_Music],
return_type=c_int)
_Mix_FilterFunc = CFUNCTYPE(None, c_void_p, POINTER(c_ubyte), c_int)
def _make_filter(func, udata):
if func:
def f(ignored, stream, len):
# FIXME: getting a negative len value here sometimes
if len < 0: return
stream = array.SDL_array(stream, len, c_ubyte)
func(udata, stream)
return _Mix_FilterFunc(f)
else:
return _Mix_FilterFunc()
_Mix_SetPostMix = _dll.private_function('Mix_SetPostMix',
arg_types=[_Mix_FilterFunc, c_void_p],
return_type=None)
_mix_postmix_ref = None
def Mix_SetPostMix(mix_func, udata):
'''Set a function that is called after all mixing is performed.
This can be used to provide real-time visual display of the audio
stream or add a custom mixer filter for the stream data.
:Parameters
`mix_func` : function
The function must have the signature
(stream: `SDL_array`, udata: any) -> None. The first argument
is the array of audio data that may be modified in place.
`udata` is the value passed in this function.
`udata` : any
A variable that is passed to the `mix_func` function each
call.
'''
global _mix_postmix_ref
_mix_postmix_ref = _make_filter(mix_func, udata)
_Mix_SetPostMix(_mix_postmix_ref, None)
_Mix_HookMusic = _dll.private_function('Mix_HookMusic',
arg_types=[_Mix_FilterFunc, c_void_p],
return_type=None)
_hookmusic_ref = None
def Mix_HookMusic(mix_func, udata):
'''Add your own music player or additional mixer function.
If `mix_func` is None, the default music player is re-enabled.
:Parameters
`mix_func` : function
The function must have the signature
(stream: `SDL_array`, udata: any) -> None. The first argument
is the array of audio data that may be modified in place.
`udata` is the value passed in this function.
`udata` : any
A variable that is passed to the `mix_func` function each
call.
'''
global _hookmusic_ref
_hookmusic_ref = _make_filter(mix_func, udata)
_Mix_HookMusic(_hookmusic_ref, None)
_Mix_HookMusicFinishedFunc = CFUNCTYPE(None)
_Mix_HookMusicFinished = _dll.private_function('Mix_HookMusicFinished',
arg_types=[_Mix_HookMusicFinishedFunc],
return_type=None)
def Mix_HookMusicFinished(music_finished):
'''Add your own callback when the music has finished playing.
This callback is only called if the music finishes naturally.
:Parameters:
`music_finished` : function
The callback takes no arguments and returns no value.
'''
if music_finished:
_Mix_HookMusicFinished(_Mix_HookMusicFinishedFunc(music_finished))
else:
_Mix_HookMusicFinished(_Mix_HookMusicFinishedFunc())
# Mix_GetMusicHookData not implemented (unnecessary)
_Mix_ChannelFinishedFunc = CFUNCTYPE(None, c_int)
_Mix_ChannelFinished = _dll.private_function('Mix_ChannelFinished',
arg_types=[_Mix_ChannelFinishedFunc],
return_type=None)
# Keep the ctypes func around
_channelfinished_ref = None
def Mix_ChannelFinished(channel_finished):
'''Add your own callback when a channel has finished playing.
The callback may be called from the mixer's audio callback or it
could be called as a result of `Mix_HaltChannel`, etc.
Do not call `SDL_LockAudio` from this callback; you will either be
inside the audio callback, or SDL_mixer will explicitly lock the
audio before calling your callback.
:Parameters:
`channel_finished` : function
The function takes the channel number as its only argument,
and returns None. Pass None here to disable the callback.
'''
global _channelfinished_ref
if channel_finished:
_channelfinished_ref = _Mix_ChannelFinishedFunc(channel_finished)
else:
_channelfinished_ref = _Mix_ChannelFinishedFunc()
_Mix_ChannelFinished(_channelfinished_ref)
_Mix_EffectFunc = CFUNCTYPE(None, c_int, POINTER(c_ubyte), c_int, c_void_p)
def _make_Mix_EffectFunc(func, udata):
if func:
def f(chan, stream, len, ignored):
stream = array.SDL_array(stream, len, c_ubyte)
func(chan, stream, udata)
return _Mix_EffectFunc(f)
else:
return _Mix_EffectFunc()
_Mix_EffectDoneFunc = CFUNCTYPE(None, c_int, c_void_p)
def _make_Mix_EffectDoneFunc(func, udata):
if func:
def f(chan, ignored):
func(chan, udata)
return _MixEffectDoneFunc(f)
else:
return _MixEffectDoneFunc()
_Mix_RegisterEffect = _dll.private_function('Mix_RegisterEffect',
arg_types=\
[c_int, _Mix_EffectFunc, _Mix_EffectDoneFunc, c_void_p],
return_type=c_int,
error_return=0)
_effect_func_refs = []
def Mix_RegisterEffect(chan, f, d, arg):
'''Register a special effect function.
At mixing time, the channel data is copied into a buffer and passed
through each registered effect function. After it passes through all
the functions, it is mixed into the final output stream. The copy to
buffer is performed once, then each effect function performs on the
output of the previous effect. Understand that this extra copy to a
buffer is not performed if there are no effects registered for a given
chunk, which saves CPU cycles, and any given effect will be extra
cycles, too, so it is crucial that your code run fast. Also note that
the data that your function is given is in the format of the sound
device, and not the format you gave to `Mix_OpenAudio`, although they
may in reality be the same. This is an unfortunate but necessary speed
concern. Use `Mix_QuerySpec` to determine if you can handle the data
before you register your effect, and take appropriate actions.
You may also specify a callback (`d`) that is called when the channel
finishes playing. This gives you a more fine-grained control than
`Mix_ChannelFinished`, in case you need to free effect-specific
resources, etc. If you don't need this, you can specify None.
You may set the callbacks before or after calling `Mix_PlayChannel`.
Things like `Mix_SetPanning` are just internal special effect
functions, so if you are using that, you've already incurred the
overhead of a copy to a separate buffer, and that these effects will be
in the queue with any functions you've registered. The list of
registered effects for a channel is reset when a chunk finishes
playing, so you need to explicitly set them with each call to
``Mix_PlayChannel*``.
You may also register a special effect function that is to be run after
final mixing occurs. The rules for these callbacks are identical to
those in `Mix_RegisterEffect`, but they are run after all the channels
and the music have been mixed into a single stream, whereas
channel-specific effects run on a given channel before any other mixing
occurs. These global effect callbacks are call "posteffects".
Posteffects only have their `d` function called when they are
unregistered (since the main output stream is never "done" in the same
sense as a channel). You must unregister them manually when you've had
enough. Your callback will be told that the channel being mixed is
(`MIX_CHANNEL_POST`) if the processing is considered a posteffect.
After all these effects have finished processing, the callback
registered through `Mix_SetPostMix` runs, and then the stream goes to
the audio device.
Do not call `SDL_LockAudio` from your callback function.
:Parameters:
`chan` : int
Channel to set effect on, or `MIX_CHANNEL_POST` for postmix.
`f` : function
Callback function for effect. Must have the signature
(channel: int, stream: `SDL_array`, udata: any) -> None;
where channel is the channel being affected, stream contains
the audio data and udata is the user variable passed in to
this function.
`d` : function
Callback function for when the effect is done. The function
must have the signature (channel: int, udata: any) -> None.
`arg` : any
User data passed to both callbacks.
'''
f = _make_MixEffectFunc(f, arg)
d = _make_MixEffectDoneFunc(d, arg)
_effect_func_refs.append(f)
_effect_func_refs.append(d)
# TODO: override EffectDone callback to remove refs and prevent
# memory leak. Be careful with MIX_CHANNEL_POST
_Mix_RegisterEffect(chan, f, d, arg)
# Mix_UnregisterEffect cannot be implemented
Mix_UnregisterAllEffects = _dll.function('Mix_UnregisterAllEffects',
'''Unregister all effects for a channel.
You may not need to call this explicitly, unless you need to stop all
effects from processing in the middle of a chunk's playback. Note that
this will also shut off some internal effect processing, since
`Mix_SetPanning` and others may use this API under the hood. This is
called internally when a channel completes playback.
Posteffects are never implicitly unregistered as they are for channels,
but they may be explicitly unregistered through this function by
specifying `MIX_CHANNEL_POST` for a channel.
:Parameters:
- `channel`: int
''',
args=['channel'],
arg_types=[c_int],
return_type=c_int,
error_return=0)
Mix_SetPanning = _dll.function('Mix_SetPanning',
'''Set the panning of a channel.
The left and right channels are specified as integers between 0 and
255, quietest to loudest, respectively.
Technically, this is just individual volume control for a sample with
two (stereo) channels, so it can be used for more than just panning.
If you want real panning, call it like this::
Mix_SetPanning(channel, left, 255 - left)
Setting (channel) to `MIX_CHANNEL_POST` registers this as a posteffect, and
the panning will be done to the final mixed stream before passing it on
to the audio device.
This uses the `Mix_RegisterEffect` API internally, and returns without
registering the effect function if the audio device is not configured
for stereo output. Setting both (left) and (right) to 255 causes this
effect to be unregistered, since that is the data's normal state.
:Parameters:
- `channel`: int
- `left`: int
- `right`: int
''',
args=['channel', 'left', 'right'],
arg_types=[c_int, c_ubyte, c_ubyte],
return_type=c_int,
error_return=0)
Mix_SetPosition = _dll.function('Mix_SetPosition',
'''Set the position of a channel.
`angle` is an integer from 0 to 360, that specifies the location of the
sound in relation to the listener. `angle` will be reduced as neccesary
(540 becomes 180 degrees, -100 becomes 260). Angle 0 is due north, and
rotates clockwise as the value increases. For efficiency, the
precision of this effect may be limited (angles 1 through 7 might all
produce the same effect, 8 through 15 are equal, etc). `distance` is
an integer between 0 and 255 that specifies the space between the sound
and the listener. The larger the number, the further away the sound is.
Using 255 does not guarantee that the channel will be culled from the
mixing process or be completely silent. For efficiency, the precision
of this effect may be limited (distance 0 through 5 might all produce
the same effect, 6 through 10 are equal, etc). Setting `angle` and
`distance` to 0 unregisters this effect, since the data would be
unchanged.
If you need more precise positional audio, consider using OpenAL for
spatialized effects instead of SDL_mixer. This is only meant to be a
basic effect for simple "3D" games.
If the audio device is configured for mono output, then you won't get
any effectiveness from the angle; however, distance attenuation on the
channel will still occur. While this effect will function with stereo
voices, it makes more sense to use voices with only one channel of
sound, so when they are mixed through this effect, the positioning will
sound correct. You can convert them to mono through SDL before giving
them to the mixer in the first place if you like.
Setting `channel` to `MIX_CHANNEL_POST` registers this as a posteffect,
and the positioning will be done to the final mixed stream before
passing it on to the audio device.
This is a convenience wrapper over `Mix_SetDistance` and
`Mix_SetPanning`.
:Parameters:
- `channel`: int
- `angle`: int
- `distance`: int
''',
args=['channel', 'angle', 'distance'],
arg_types=[c_int, c_short, c_ubyte],
return_type=c_int,
error_return=0)
Mix_SetDistance = _dll.function('Mix_SetDistance',
'''Set the "distance" of a channel.
`distance` is an integer from 0 to 255 that specifies the location of
the sound in relation to the listener. Distance 0 is overlapping the
listener, and 255 is as far away as possible A distance of 255 does not
guarantee silence; in such a case, you might want to try changing the
chunk's volume, or just cull the sample from the mixing process with
`Mix_HaltChannel`.
For efficiency, the precision of this effect may be limited (distances
1 through 7 might all produce the same effect, 8 through 15 are equal,
etc). `distance` is an integer between 0 and 255 that specifies the
space between the sound and the listener. The larger the number, the
further away the sound is.
Setting `distance` to 0 unregisters this effect, since the data would
be unchanged.
If you need more precise positional audio, consider using OpenAL for
spatialized effects instead of SDL_mixer. This is only meant to be a
basic effect for simple "3D" games.
Setting `channel` to `MIX_CHANNEL_POST` registers this as a posteffect,
and the distance attenuation will be done to the final mixed stream
before passing it on to the audio device.
This uses the `Mix_RegisterEffect` API internally.
:Parameters:
- `channel`: int
- `distance`: distance
''',
args=['channel', 'distance'],
arg_types=[c_int, c_ubyte],
return_type=c_int,
error_return=0)
Mix_SetReverseStereo = _dll.function('Mix_SetReverseStereo',
'''Causes a channel to reverse its stereo.
This is handy if the user has his or her speakers hooked up backwards,
or you would like to have a minor bit of psychedelia in your sound
code. Calling this function with `flip` set to non-zero reverses the
chunks's usual channels. If `flip` is zero, the effect is unregistered.
This uses the `Mix_RegisterEffect` API internally, and thus is probably
more CPU intensive than having the user just plug in his speakers
correctly. `Mix_SetReverseStereo` returns without registering the
effect function if the audio device is not configured for stereo
output.
If you specify `MIX_CHANNEL_POST` for `channel`, then this the effect
is used on the final mixed stream before sending it on to the audio
device (a posteffect).
:Parameters:
- `channel`: int
- `flip`: int
''',
args=['channel', 'flip'],
arg_types=[c_int, c_int],
return_type=c_int,
error_return=0)
Mix_ReserveChannels = _dll.function('Mix_ReserveChannels',
'''Reserve the first channels (0 to n-1) for the application.
If reserved, a channel will not be allocated dynamically to a sample
if requested with one of the ``Mix_Play*`` functions.
:Parameters:
- `num`: int
:rtype: int
:return: the number of reserved channels
''',
args=['num'],
arg_types=[c_int],
return_type=c_int)
Mix_GroupChannel = _dll.function('Mix_GroupChannel',
'''Assing a channel to a group.
A tag can be assigned to several mixer channels, to form groups
of channels. If `tag` is -1, the tag is removed (actually -1 is the
tag used to represent the group of all the channels).
:Parameters:
- `channel`: int
- `tag`: int
''',
args=['channel', 'tag'],
arg_types=[c_int, c_int],
return_type=c_int,
error_return=0)
Mix_GroupChannels = _dll.function('Mix_GroupChannels',
'''Assign several consecutive channels to a group.
A tag can be assigned to several mixer channels, to form groups
of channels. If `tag` is -1, the tag is removed (actually -1 is the
tag used to represent the group of all the channels).
:Parameters:
- `channel_from`: int
- `channel_to`: int
- `tag`: int
''',
args=['channel_from', 'channel_to', 'tag'],
arg_types=[c_int, c_int, c_int],
return_type=c_int,
error_return=0)
Mix_GroupAvailable = _dll.function('Mix_GroupAvailable',
'''Find the first available channel in a group of channels.
:Parameters:
- `tag`: int
:rtype: int
:return: a channel, or -1 if none are available.
''',
args=['tag'],
arg_types=[c_int],
return_type=c_int)
Mix_GroupCount = _dll.function('Mix_GroupCount',
'''Get the number of channels in a group.
If `tag` is -1, returns the total number of channels.
:Parameters:
- `tag`: int
:rtype: int
''',
args=['tag'],
arg_types=[c_int],
return_type=c_int)
Mix_GroupOldest = _dll.function('Mix_GroupOldest',
'''Find the "oldest" sample playing in a group of channels.
:Parameters:
- `tag`: int
:rtype: int
''',
args=['tag'],
arg_types=[c_int],
return_type=c_int)
Mix_GroupNewer = _dll.function('Mix_GroupNewer',
'''Find the "most recent" (i.e., last) sample playing in a group of
channels.
:Parameters:
- `tag`: int
:rtype: int
''',
args=['tag'],
arg_types=[c_int],
return_type=c_int)
def Mix_PlayChannel(channel, chunk, loops):
'''Play an audio chunk on a specific channel.
:Parameters:
`channel` : int
If -1, play on the first free channel.
`chunk` : `Mix_Chunk`
Chunk to play
`loops` : int
If greater than zero, the number of times to play the sound;
if -1, loop infinitely.
:rtype: int
:return: the channel that was used to play the sound.
'''
return Mix_PlayChannelTimed(channel, chunk, loops, -1)
Mix_PlayChannelTimed = _dll.function('Mix_PlayChannelTimed',
'''Play an audio chunk on a specific channel for a specified amount of
time.
:Parameters:
`channel` : int
If -1, play on the first free channel.
`chunk` : `Mix_Chunk`
Chunk to play
`loops` : int
If greater than zero, the number of times to play the sound;
if -1, loop infinitely.
`ticks` : int
Maximum number of milliseconds to play sound for.
:rtype: int
:return: the channel that was used to play the sound.
''',
args=['channel', 'chunk', 'loops', 'ticks'],
arg_types=[c_int, POINTER(Mix_Chunk), c_int, c_int],
return_type=c_int)
Mix_PlayMusic = _dll.function('Mix_PlayMusic',
'''Play a music chunk.
:Parameters:
`music` : ``Mix_Music``
Chunk to play
`loops` : int
If greater than zero, the number of times to play the sound;
if -1, loop infinitely.
''',
args=['music', 'loops'],
arg_types=[_Mix_Music, c_int],
return_type=c_int,
error_return=-1)
Mix_FadeInMusic = _dll.function('Mix_FadeInMusic',
'''Fade in music over a period of time.
:Parameters:
`music` : ``Mix_Music``
Chunk to play
`loops` : int
If greater than zero, the number of times to play the sound;
if -1, loop infinitely.
`ms` : int
Number of milliseconds to fade up over.
''',
args=['music', 'loops', 'ms'],
arg_types=[_Mix_Music, c_int, c_int],
return_type=c_int,
error_return=-1)
Mix_FadeInMusicPos = _dll.function('Mix_FadeInMusicPos',
'''Fade in music at an offset over a period of time.
:Parameters:
`music` : ``Mix_Music``
Chunk to play
`loops` : int
If greater than zero, the number of times to play the sound;
if -1, loop infinitely.
`ms` : int
Number of milliseconds to fade up over.
`position` : float
Position within music to start at. Currently implemented
only for MOD, OGG and MP3.
:see: Mix_SetMusicPosition
''',
args=['music', 'loops', 'ms', 'position'],
arg_types=[_Mix_Music, c_int, c_int, c_double],
return_type=c_int,
error_return=-1)
def Mix_FadeInChannel(channel, chunk, loops, ms):
'''Fade in a channel.
:Parameters:
`channel` : int
If -1, play on the first free channel.
`chunk` : `Mix_Chunk`
Chunk to play
`loops` : int
If greater than zero, the number of times to play the sound;
if -1, loop infinitely.
`ms` : int
Number of milliseconds to fade up over.
'''
Mix_FadeInChannelTimed(channel, chunk, loops, -1)
Mix_FadeInChannelTimed = _dll.function('Mix_FadeInChannelTimed',
'''Fade in a channel and play for a specified amount of time.
:Parameters:
`channel` : int
If -1, play on the first free channel.
`chunk` : `Mix_Chunk`
Chunk to play
`loops` : int
If greater than zero, the number of times to play the sound;
if -1, loop infinitely.
`ms` : int
Number of milliseconds to fade up over.
`ticks` : int
Maximum number of milliseconds to play sound for.
''',
args=['channel', 'music', 'loops', 'ms', 'ticks'],
arg_types=[c_int, _Mix_Music, c_int, c_int, c_int],
return_type=c_int,
error_return=-1)
Mix_Volume = _dll.function('Mix_Volume',
'''Set the volume in the range of 0-128 of a specific channel.
:Parameters:
`channel` : int
If -1, set the volume for all channels
`volume` : int
Volume to set, in the range 0-128, or -1 to just return the
current volume.
:rtype: int
:return: the original volume.
''',
args=['channel', 'volume'],
arg_types=[c_int, c_int],
return_type=c_int)
Mix_VolumeChunk = _dll.function('Mix_VolumeChunk',
'''Set the volume in the range of 0-128 of a chunk.
:Parameters:
`chunk` : `Mix_Chunk`
Chunk to set volume.
`volume` : int
Volume to set, in the range 0-128, or -1 to just return the
current volume.
:rtype: int
:return: the original volume.
''',
args=['chunk', 'volume'],
arg_types=[POINTER(Mix_Chunk), c_int],
return_type=c_int)
Mix_VolumeMusic = _dll.function('Mix_VolumeMusic',
'''Set the volume in the range of 0-128 of the music.
:Parameters:
`volume` : int
Volume to set, in the range 0-128, or -1 to just return the
current volume.
:rtype: int
:return: the original volume.
''',
args=['volume'],
arg_types=[c_int],
return_type=c_int)
Mix_HaltChannel = _dll.function('Mix_HaltChannel',
'''Halt playing of a particular channel.
:Parameters:
- `channel`: int
''',
args=['channel'],
arg_types=[c_int],
return_type=None)
Mix_HaltGroup = _dll.function('Mix_HaltGroup',
'''Halt playing of a particular group.
:Parameters:
- `tag`: int
''',
args=['tag'],
arg_types=[c_int],
return_type=None)
Mix_HaltMusic = _dll.function('Mix_HaltMusic',
'''Halt playing music.
''',
args=[],
arg_types=[],
return_type=None)
Mix_ExpireChannel = _dll.function('Mix_ExpireChannel',
'''Change the expiration delay for a particular channel.
The sample will stop playing afte the `ticks` milliseconds have
elapsed, or remove the expiration if `ticks` is -1.
:Parameters:
- `channel`: int
- `ticks`: int
:rtype: int
:return: the number of channels affected.
''',
args=['channel', 'ticks'],
arg_types=[c_int, c_int],
return_type=c_int)
Mix_FadeOutChannel = _dll.function('Mix_FadeOutChannel',
'''Halt a channel, fading it out progressively until it's silent.
The `ms` parameter indicates the number of milliseconds the fading
will take.
:Parameters:
- `channel`: int
- `ms`: int
''',
args=['channel', 'ms'],
arg_types=[c_int, c_int],
return_type=None)
Mix_FadeOutGroup = _dll.function('Mix_FadeOutGroup',
'''Halt a group, fading it out progressively until it's silent.
The `ms` parameter indicates the number of milliseconds the fading
will take.
:Parameters:
- `tag`: int
- `ms`: int
''',
args=['tag', 'ms'],
arg_types=[c_int, c_int],
return_type=None)
Mix_FadeOutMusic = _dll.function('Mix_FadeOutMusic',
'''Halt playing music, fading it out progressively until it's silent.
The `ms` parameter indicates the number of milliseconds the fading
will take.
:Parameters:
- `ms`: int
''',
args=['ms'],
arg_types=[c_int],
return_type=None)
Mix_FadingMusic = _dll.function('Mix_FadingMusic',
'''Query the fading status of the music.
:rtype: int
:return: one of MIX_NO_FADING, MIX_FADING_OUT, MIX_FADING_IN.
''',
args=[],
arg_types=[],
return_type=c_int)
Mix_FadingChannel = _dll.function('Mix_FadingChannel',
'''Query the fading status of a channel.
:Parameters:
- `channel`: int
:rtype: int
:return: one of MIX_NO_FADING, MIX_FADING_OUT, MIX_FADING_IN.
''',
args=['channel'],
arg_types=[c_int],
return_type=c_int)
Mix_Pause = _dll.function('Mix_Pause',
'''Pause a particular channel.
:Parameters:
- `channel`: int
''',
args=['channel'],
arg_types=[c_int],
return_type=None)
Mix_Resume = _dll.function('Mix_Resume',
'''Resume a particular channel.
:Parameters:
- `channel`: int
''',
args=['channel'],
arg_types=[c_int],
return_type=None)
Mix_Paused = _dll.function('Mix_Paused',
'''Query if a channel is paused.
:Parameters:
- `channel`: int
:rtype: int
''',
args=['channel'],
arg_types=[c_int],
return_type=c_int)
Mix_PauseMusic = _dll.function('Mix_PauseMusic',
'''Pause the music stream.
''',
args=[],
arg_types=[],
return_type=None)
Mix_ResumeMusic = _dll.function('Mix_ResumeMusic',
'''Resume the music stream.
''',
args=[],
arg_types=[],
return_type=None)
Mix_RewindMusic = _dll.function('Mix_RewindMusic',
'''Rewind the music stream.
''',
args=[],
arg_types=[],
return_type=None)
Mix_PausedMusic = _dll.function('Mix_PausedMusic',
'''Query if the music stream is paused.
:rtype: int
''',
args=[],
arg_types=[],
return_type=c_int)
Mix_SetMusicPosition = _dll.function('Mix_SetMusicPosition',
'''Set the current position in the music stream.
For MOD files the position represents the pattern order number;
for OGG and MP3 files the position is in seconds. Currently no other
music file formats support positioning.
:Parameters:
- `position`: float
''',
args=['position'],
arg_types=[c_double],
return_type=c_int,
error_return=-1)
Mix_Playing = _dll.function('Mix_Playing',
'''Query the status of a specific channel.
:Parameters:
- `channel`: int
:rtype: int
:return: the number of queried channels that are playing.
''',
args=['channel'],
arg_types=[c_int],
return_type=c_int)
Mix_PlayingMusic = _dll.function('Mix_PlayingMusic',
'''Query the status of the music stream.
:rtype: int
:return: 1 if music is playing, 0 otherwise.
''',
args=[],
arg_types=[],
return_type=c_int)
Mix_SetMusicCMD = _dll.function('Mix_SetMusicCMD',
'''Set the external music playback command.
Any currently playing music will stop.
:Parameters:
- `command`: string
''',
args=['command'],
arg_types=[c_char_p],
return_type=c_int,
error_return=-1)
Mix_SetSynchroValue = _dll.function('Mix_SetSynchroValue',
'''Set the synchro value for a MOD music stream.
:Parameters:
- `value`: int
''',
args=['value'],
arg_types=[c_int],
return_type=c_int,
error_return=-1)
Mix_GetSynchroValue = _dll.function('Mix_GetSynchroValue',
'''Get the synchro value for a MOD music stream.
:rtype: int
''',
args=[],
arg_types=[],
return_type=c_int)
Mix_GetChunk = _dll.function('Mix_GetChunk',
'''Get the chunk currently associated with a mixer channel.
Returns None if the channel is invalid or if there's no chunk associated.
:Parameters:
- `channel`: int
:rtype: `Mix_Chunk`
''',
args=['channel'],
arg_types=[c_int],
return_type=POINTER(Mix_Chunk),
dereference_return=True)
Mix_CloseAudio = _dll.function('Mix_CloseAudio',
'''Close the mixer, halting all playing audio.
''',
args=[],
arg_types=[],
return_type=None)
| Python |
#!/usr/bin/env python
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
class SDL_array:
def __init__(self, ptr, count, ctype):
'''Construct an array at memory location `ptr` with `count` elements
of type `ctype`.
:Parameters:
`ptr` : ctypes.Array, POINTER(ctype) or POINTER(ctypes.Array)
Starting point of the array space. Don't use c_void_p; this
will not cast correctly. If `ptr` is None, the array
will be created (filled with random data).
`count` : int
Number of elements in the array.
`ctype` : type
ctypes type if each element, e.g., c_ubyte, c_int, etc.
'''
count = int(count)
assert count >= 0
if not ptr:
ptr = (ctype * count)()
self.ptr = ptr
self.count = count
self.ctype = ctype
self._ctypes_array = None
# Casting methods
def as_bytes(self):
'''Access the array as raw bytes, regardless of the underlying
data type.
This can be useful, for example, in accessing a 32-bit colour
buffer by individual components rather than the encoded pixel.
:rtype: SDL_array
'''
return SDL_array(self.ptr, (self.count * sizeof(self.ctype)), c_ubyte)
def as_int16(self):
'''Access the array as 16-bit integers, regardless of the underlying
data type.
:rtype: SDL_array
'''
return SDL_array(self.ptr,
self.count * sizeof(self.ctype) / 2,
c_ushort)
def as_int32(self):
'''Access the array as 32-bit integers, regardless of the underlying
data type.
:rtype: SDL_array
'''
return SDL_array(self.ptr,
self.count * sizeof(self.ctype) / 4,
c_uint)
def as_ctypes(self):
'''Access the array as a ctypes array.
:rtype: ctypes.Array
'''
if not self._ctypes_array:
self._ctypes_array = \
cast(self.ptr, POINTER(self.ctype * self.count)).contents
return self._ctypes_array
# numpy specific methods
def have_numpy(cls):
'''Determine if the numpy array module is available.
:rtype: bool
'''
return _have_numpy
def as_numpy(self, shape=None):
'''Access the array as a numpy array.
The numpy array shares the same underlying memory buffer, so
changes are immediate, and you can use the numpy array as you would
normally. To set the entire contents of the array at once, use a
``[:]`` slice.
If numpy is not installed, an ImportError will be raised.
:rtype: numpy.ndarray
'''
if not _have_numpy:
raise ImportError, 'numpy could not be imported'
if self.ctype not in _numpy_typemap:
raise TypeError, '%s has no numpy compatible type' % self.ctype
if shape is None:
shape = (self.count,)
ar = numpy.frombuffer(self.as_ctypes(), _numpy_typemap[self.ctype])
ar = ar.reshape(shape)
return ar
# General interoperability (string)
def to_string(self):
'''Return a string with the contents of this array.
:rtype: string
'''
count = sizeof(self.ctype) * self.count
s = create_string_buffer(count)
memmove(s, self.ptr, count)
return s.raw
def from_string(self, data):
'''Copy string data into this array.
The string must have exactly the same length of this array (in bytes).
No size checking is performed.
:Parameters:
`data` : str
String data to copy.
'''
memmove(self.ptr, data, len(data))
def __repr__(self):
return 'SDL_array(ctype=%s, count=%r)' % (self.ctype, self.count)
def __len__(self):
return self.count
def __getitem__(self, key):
if type(key) is slice:
if key.step:
raise TypeError, 'slice step not supported'
return self.as_ctypes()[key.start:key.stop]
else:
return self.as_ctypes()[key]
def __setitem__(self, key, value):
if type(key) is slice:
if key.step:
raise TypeError, 'slice step not supported'
self.as_ctypes()[key.start:key.stop] = value
else:
self.as_ctypes()[key] = value
def to_ctypes(values, count, ctype):
'''Create a ctypes array of the given count and type, with the contents
of sequence `values`.
:Parameters:
- `values`: sequence of length `count`, or SDL_array instance, or
ctypes.Array, or POINTER(ctypes.Array)
- `count`: int
- `ctype`: type
:rtype: object, ctypes.Array
:return: (ref, array), where ref is an object that must be retained
by the caller for as long as the array is used.
'''
ref = values
# Convert SDL_array instances to ctypes array
if isinstance(values, SDL_array):
values = values.as_ctypes()
# Cast ctypes array to correct type if necessary
if isinstance(values, Array):
if values._type_ is ctype:
return ref, values
else:
return ref, cast(values, POINTER(ctype * count)).contents
# Convert string bytes to array
if type(values) == str:
ref = create_string_buffer(values)
return ref, cast(ref, POINTER(ctype * count)).contents
# Otherwise assume sequence
ar = (ctype * count)(*values)
return ar, ar
| Python |
#!/usr/bin/env python
'''Functions for converting to native byte order
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import sys
from cocos.audio.SDL.constants import SDL_BIG_ENDIAN, SDL_LIL_ENDIAN
def SDL_Swap16(x):
return (x << 8 & 0xff00) | \
(x >> 8 & 0x00ff)
def SDL_Swap32(x):
return (x << 24 & 0xff000000) | \
(x << 8 & 0x00ff0000) | \
(x >> 8 & 0x0000ff00) | \
(x >> 24 & 0x000000ff)
def SDL_Swap64(x):
return (SDL_Swap32(x & 0xffffffff) << 32) | \
(SDL_Swap32(x >> 32 & 0xffffffff))
def _noop(x):
return x
if sys.byteorder == 'big':
SDL_BYTEORDER = SDL_BIG_ENDIAN
SDL_SwapLE16 = SDL_Swap16
SDL_SwapLE32 = SDL_Swap32
SDL_SwapLE64 = SDL_Swap64
SDL_SwapBE16 = _noop
SDL_SwapBE32 = _noop
SDL_SwapBE64 = _noop
else:
SDL_BYTEORDER = SDL_LIL_ENDIAN
SDL_SwapLE16 = _noop
SDL_SwapLE32 = _noop
SDL_SwapLE64 = _noop
SDL_SwapBE16 = SDL_Swap16
SDL_SwapBE32 = SDL_Swap32
SDL_SwapBE64 = SDL_Swap64
| Python |
#!/usr/bin/env python
'''General interface for SDL to read and write data sources.
For files, use `SDL_RWFromFile`. Other Python file-type objects can be
used with `SDL_RWFromObject`. If another library provides a constant void
pointer to a contiguous region of memory, `SDL_RWFromMem` and
`SDL_RWFromConstMem` can be used.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
import dll
import constants
_rwops_p = POINTER('SDL_RWops')
_seek_fn = CFUNCTYPE(c_int, _rwops_p, c_int, c_int)
_read_fn = CFUNCTYPE(c_int, _rwops_p, c_void_p, c_int, c_int)
_write_fn = CFUNCTYPE(c_int, _rwops_p, c_void_p, c_int, c_int)
_close_fn = CFUNCTYPE(c_int, _rwops_p)
class _hidden_mem_t(Structure):
_fields_ = [('base', c_void_p),
('here', c_void_p),
('stop', c_void_p)]
class SDL_RWops(Structure):
'''Read/write operations structure.
:Ivariables:
`seek` : function
seek(context: `SDL_RWops`, offset: int, whence: int) -> int
`read` : function
read(context: `SDL_RWops`, ptr: c_void_p, size: int, maxnum: int)
-> int
`write` : function
write(context: `SDL_RWops`, ptr: c_void_p, size: int, num: int) ->
int
`close` : function
close(context: `SDL_RWops`) -> int
`type` : int
Undocumented
'''
_fields_ = [('seek', _seek_fn),
('read', _read_fn),
('write', _write_fn),
('close', _close_fn),
('type', c_uint),
('_hidden_mem', _hidden_mem_t)]
SetPointerType(_rwops_p, SDL_RWops)
SDL_RWFromFile = dll.function('SDL_RWFromFile',
'''Create an SDL_RWops structure from a file on disk.
:Parameters:
`file` : string
Filename
`mode` : string
Mode to open the file with; as with the built-in function ``open``.
:rtype: `SDL_RWops`
''',
args=['file', 'mode'],
arg_types=[c_char_p, c_char_p],
return_type=POINTER(SDL_RWops),
dereference_return=True,
require_return=True)
SDL_RWFromMem = dll.function('SDL_RWFromMem',
'''Create an SDL_RWops structure from a contiguous region of memory.
:Parameters:
- `mem`: ``c_void_p``
- `size`: int
:rtype: `SDL_RWops`
''',
args=['mem', 'size'],
arg_types=[c_void_p, c_int],
return_type=POINTER(SDL_RWops),
dereference_return=True,
require_return=True)
SDL_RWFromConstMem = dll.function('SDL_RWFromConstMem',
'''Create an SDL_RWops structure from a contiguous region of memory.
:Parameters:
- `mem`: ``c_void_p``
- `size`: int
:rtype: `SDL_RWops`
:since: 1.2.7
''',
args=['mem', 'size'],
arg_types=[c_void_p, c_int],
return_type=POINTER(SDL_RWops),
dereference_return=True,
require_return=True,
since=(1,2,7))
""" These functions shouldn't be useful to Pythoners.
SDL_AllocRW = dll.function('SDL_AllocRW',
'''Allocate a blank SDL_Rwops structure.
:rtype: `SDL_RWops`
'''
args=[],
arg_types=[],
return_type=POINTER(SDL_RWops),
dereference_return=True,
require_return=True)
SDL_FreeRW = dll.function('SDL_FreeRW',
'''Free a SDL_RWops structure.
:param area: `SDL_RWops`
'''
args=['area'],
arg_types=[POINTER(SDL_RWops)],
return_type=None)
"""
# XXX Tested read from open() only so far
def SDL_RWFromObject(obj):
'''Construct an SDL_RWops structure from a Python file-like object.
The object must support the following methods in the same fashion as
the builtin file object:
- ``read(len) -> data``
- ``write(data)``
- ``seek(offset, whence)``
- ``close()``
:Parameters:
- `obj`: Python file-like object to wrap
:rtype: `SDL_RWops`
'''
ctx = SDL_RWops()
def _seek(context, offset, whence):
obj.seek(offset, whence)
return obj.tell()
ctx.seek = _seek_fn(_seek)
def _read(context, ptr, size, maximum):
try:
r = obj.read(maximum * size)
memmove(ptr, r, len(r))
return len(r) / size
except:
return -1
ctx.read = _read_fn(_read)
def _write(context, ptr, size, num):
try:
obj.write(string_at(ptr, size*num))
return num
except:
return -1
ctx.write = _write_fn(_write)
def _close(context):
obj.close()
ctx.close = _close_fn(_close)
return ctx
"""
# XXX Usefulness of the following using raw pointers?
def SDL_RWseek(ctx, offset, whence):
return ctx.seek(ctx, offset, whence)
def SDL_RWtell(ctx):
return ctx.seek(ctx, 0, constants.RW_SEEK_CUR)
def SDL_RWread(ctx, ptr, size, n):
return ctx.read(ctx, ptr, size, n)
def SDL_RWwrite(ctx, ptr, size, n):
return ctx.write(ctx, ptr, size, n)
def SDL_RWclose(ctx):
return ctx.close(ctx)
"""
# XXX not implemented: SDL_Read{BL}E* and SDL_Write{BL}E*
| Python |
#!/usr/bin/env python
'''Access to the raw audio mixing buffer.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
import sys
import array
import constants
import dll
import rwops
_SDL_AudioSpec_fn = \
CFUNCTYPE(POINTER(c_ubyte), POINTER(c_ubyte), POINTER(c_ubyte), c_int)
class SDL_AudioSpec(Structure):
'''Audio format structure.
The calculated values in this structure are calculated by `SDL_OpenAudio`.
:Ivariables:
`freq` : int
DSP frequency, in samples per second
`format` : int
Audio data format. One of AUDIO_U8, AUDIO_S8, AUDIO_U16LSB,
AUDIO_S16LSB, AUDIO_U16MSB or AUDIO_S16MSB
`channels` : int
Number of channels; 1 for mono or 2 for stereo.
`silence` : int
Audio buffer silence value (calculated)
`samples` : int
Audio buffer size in samples (power of 2)
`size` : int
Audio buffer size in bytes (calculated)
'''
_fields_ = [('freq', c_int),
('format', c_ushort),
('channels', c_ubyte),
('silence', c_ubyte),
('samples', c_ushort),
('_padding', c_ushort),
('size', c_uint),
('_callback', _SDL_AudioSpec_fn),
('_userdata', c_void_p)]
_SDL_AudioCVT_p = POINTER('SDL_AudioCVT')
_SDL_AudioCVT_filter_fn = \
CFUNCTYPE(POINTER(c_ubyte), _SDL_AudioCVT_p, c_ushort)
class SDL_AudioCVT(Structure):
'''Set of audio conversion filters and buffers.
:Ivariables:
`needed` : int
1 if conversion is possible
`src_format` : int
Source audio format. See `SDL_AudioSpec.format`
`dst_format` : int
Destination audio format. See `SDL_AudioSpec.format`
`rate_incr` : float
Rate conversion increment
`len` : int
Length of original audio buffer
`len_cvt` : int
Length of converted audio buffer
`len_mult` : int
Buffer must be len * len_mult big
`len_ratio` : float
Given len, final size is len * len_ratio
`filter_index` : int
Current audio conversion function
'''
_fields_ = [('needed', c_int),
('src_format', c_ushort),
('dst_format', c_ushort),
('rate_incr', c_double),
('buf', POINTER(c_ubyte)),
('len', c_int),
('len_cvt', c_int),
('len_mult', c_int),
('len_ratio', c_double),
('filters', _SDL_AudioCVT_filter_fn * 10),
('filter_index', c_int)]
SetPointerType(_SDL_AudioCVT_p, SDL_AudioCVT)
# SDL_AudioInit and SDL_AudioQuit marked private
_SDL_AudioDriverName = dll.private_function('SDL_AudioDriverName',
arg_types=[c_char_p, c_int],
return_type=c_char_p)
def SDL_AudioDriverName(maxlen=1024):
'''
Returns the name of the audio driver. Returns None if no driver has
been initialised.
:Parameters:
`maxlen`
Maximum length of the returned driver name; defaults to 1024.
:rtype: string
'''
buf = create_string_buffer(maxlen)
if _SDL_AudioDriverName(buf, maxlen):
return buf.value
return None
def _ctype_audio_format(fmt):
if fmt == constants.AUDIO_U8:
return c_ubyte
elif fmt == constants.AUDIO_S8:
return c_char
elif fmt in (constants.AUDIO_U16LSB, constants.AUDIO_U16MSB):
return c_ushort
elif fmt in (constants.AUDIO_S16LSB, constants.AUDIO_S16MSB):
return c_short
else:
raise TypeError, 'Unsupported format %r' % fmt
_SDL_OpenAudio = dll.private_function('SDL_OpenAudio',
arg_types=[POINTER(SDL_AudioSpec), POINTER(SDL_AudioSpec)],
return_type=c_int,
error_return=-1)
def SDL_OpenAudio(desired, obtained):
'''Open the audio device with the desired parameters.
If successful, the actual hardware parameters will be set in the
instance passed into `obtained`. If `obtained` is None, the audio
data passed to the callback function will be guaranteed to be in
the requested format, and will be automatically converted to the
hardware audio format if necessary.
An exception will be raised if the audio device couldn't be opened,
or the audio thread could not be set up.
The fields of `desired` are interpreted as follows:
`desired.freq`
desired audio frequency in samples per second
`desired.format`
desired audio format, i.e., one of AUDIO_U8, AUDIO_S8,
AUDIO_U16LSB, AUDIO_S16LSB, AUDIO_U16MSB or AUDIO_S16MSB
`desired.samples`
size of the audio buffer, in samples. This number should
be a power of two, and may be adjusted by the audio driver
to a value more suitable for the hardware. Good values seem
to range between 512 and 8096 inclusive, depending on the
application and CPU speed. Smaller values yield faster response
time, but can lead to underflow if the application is doing
heavy processing and cannot fill the audio buffer in time.
A stereo sample consists of both right and left channels in
LR ordering. Note that the number of samples is directly
related to time by the following formula::
ms = (samples * 1000) / freq
`desired.size`
size in bytes of the audio buffer; calculated by SDL_OpenAudio.
`desired.silence`
value used to set the buffer to silence; calculated by
SDL_OpenAudio.
`desired.callback`
a function that will be called when the audio device is ready
for more data. The signature of the function should be::
callback(userdata: any, stream: SDL_array) -> None
The function is called with the userdata you specify (see below),
and an SDL_array of the obtained format which you must fill
with audio data.
This function usually runs in a separate thread, so you should
protect data structures that it accesses by calling
`SDL_LockAudio` and `SDL_UnlockAudio` in your code.
`desired.userdata`
passed as the first parameter to your callback function.
The audio device starts out playing silence when it's opened, and should
be enabled for playing by calling ``SDL_PauseAudio(False)`` when you are
ready for your audio callback function to be called. Since the audio
driver may modify the requested size of the audio buffer, you should
allocate any local mixing buffers after you open the audio device.
:Parameters:
- `desired`: `SDL_AudioSpec`
- `obtained`: `SDL_AudioSpec` or None
'''
if not hasattr(desired, 'callback'):
raise TypeError, 'Attribute "callback" not set on "desired"'
userdata = getattr(desired, 'userdata', None)
callback = desired.callback
ctype = [_ctype_audio_format(desired.format)] # List, so mutable
def cb(data, stream, len):
ar = array.SDL_array(stream, len/sizeof(ctype[0]), ctype[0])
callback(userdata, ar)
desired._callback = _SDL_AudioSpec_fn(cb)
_SDL_OpenAudio(desired, obtained)
if obtained:
obtained.userdata = desired.userdata
obtained.callback = desired.callback
ctype[0] = _ctype_audio_format(obtained.format)
SDL_GetAudioStatus = dll.function('SDL_GetAudioStatus',
'''Get the current audio state.
:rtype: int
:return: one of SDL_AUDIO_STOPPED, SDL_AUDIO_PLAYING, SDL_AUDIO_PAUSED
''',
args=[],
arg_types=[],
return_type=c_int)
SDL_PauseAudio = dll.function('SDL_PauseAudio',
'''Pause and unpause the audio callback processing.
It should be called with a parameter of 0 after opening the audio
device to start playing sound. This is so you can safely initalize
data for your callback function after opening the audio device.
Silence will be written to the audio device during the pause.
:Parameters:
- `pause_on`: int
''',
args=['pause_on'],
arg_types=[c_int],
return_type=None)
_SDL_LoadWAV_RW = dll.private_function('SDL_LoadWAV_RW',
arg_types=[POINTER(rwops.SDL_RWops),
c_int,
POINTER(SDL_AudioSpec),
POINTER(POINTER(c_ubyte)),
POINTER(c_uint)],
return_type=POINTER(SDL_AudioSpec),
require_return=True)
def SDL_LoadWAV_RW(src, freesrc):
'''Load a WAVE from the data source.
The source is automatically freed if `freesrc` is non-zero. For
example, to load a WAVE file, you could do::
SDL_LoadWAV_RW(SDL_RWFromFile('sample.wav', 'rb'), 1)
You need to free the returned buffer with `SDL_FreeWAV` when you
are done with it.
:Parameters:
- `src`: `SDL_RWops`
- `freesrc`: int
:rtype: (`SDL_AudioSpec`, `SDL_array`)
:return: a tuple (`spec`, `audio_buf`) where `spec` describes the data
format and `audio_buf` is the buffer containing audio data.
'''
spec = SDL_AudioSpec()
audio_buf = POINTER(c_ubyte)()
audio_len = c_uint()
_SDL_LoadWAV_RW(src, freesrc, spec, byref(audio_buf), byref(audio_len))
ctype = _ctype_audio_format(spec.format)
return (spec,
array.SDL_array(audio_buf, audio_len.value/sizeof(ctype), ctype))
def SDL_LoadWAV(file):
'''Load a WAVE from a file.
:Parameters:
- `file`: str
:rtype: (`SDL_AudioSpec`, `SDL_array`)
:see: `SDL_LoadWAV_RW`
'''
return SDL_LoadWAV_RW(rwops.SDL_RWFromFile(file, 'rb'), 1)
_SDL_FreeWAV = dll.private_function('SDL_FreeWAV',
arg_types=[POINTER(c_ubyte)],
return_type=None)
def SDL_FreeWAV(audio_buf):
'''Free a buffer previously allocated with `SDL_LoadWAV_RW` or
`SDL_LoadWAV`.
:Parameters:
- `audio_buf`: `SDL_array`
'''
_SDL_FreeWAV(audio_buf.as_bytes().as_ctypes())
_SDL_BuildAudioCVT = dll.private_function('SDL_BuildAudioCVT',
arg_types=[POINTER(SDL_AudioCVT), c_ushort, c_ubyte, c_uint,
c_ushort, c_ubyte, c_uint],
return_type=c_int,
error_return=-1)
def SDL_BuildAudioCVT(src_format, src_channels, src_rate,
dst_format, dst_channels, dst_rate):
'''Take a source format and rate and a destination format and rate,
and return a `SDL_AudioCVT` structure.
The `SDL_AudioCVT` structure is used by `SDL_ConvertAudio` to convert
a buffer of audio data from one format to the other.
:Parameters:
- `src_format`: int
- `src_channels`: int
- `src_rate`: int
- `dst_format`: int
- `dst_channels`: int
- `dst_rate`: int
:rtype: `SDL_AudioCVT`
'''
cvt = SDL_AudioCVT()
_SDL_BuildAudioCVT(cvt, src_format, src_channels, src_rate,
dst_format, dst_channels, dst_rate)
return cvt
SDL_ConvertAudio = dll.function('SDL_ConvertAudio',
'''Convert audio data in-place.
Once you have initialized the 'cvt' structure using
`SDL_BuildAudioCVT`, created an audio buffer ``cvt.buf``, and filled it
with ``cvt.len`` bytes of audio data in the source format, this
function will convert it in-place to the desired format. The data
conversion may expand the size of the audio data, so the buffer
``cvt.buf`` should be allocated after the cvt structure is initialized
by `SDL_BuildAudioCVT`, and should be ``cvt->len*cvt->len_mult`` bytes
long.
Note that you are responsible for allocating the buffer. The
recommended way is to construct an `SDL_array` of the correct size,
and set ``cvt.buf`` to the result of `SDL_array.as_ctypes`.
:Parameters:
- `cvt`: `SDL_AudioCVT`
:rtype: int
:return: undocumented
''',
args=['cvt'],
arg_types=[POINTER(SDL_AudioCVT)],
return_type=c_int)
_SDL_MixAudio = dll.private_function('SDL_MixAudio',
arg_types=[POINTER(c_ubyte), POINTER(c_ubyte), c_uint, c_int],
return_type=None)
def SDL_MixAudio(dst, src, length, volume):
'''Mix two audio buffers.
This takes two audio buffers of the playing audio format and mixes
them, performing addition, volume adjustment, and overflow clipping.
The volume ranges from 0 - 128, and should be set to SDL_MIX_MAXVOLUME
for full audio volume. Note this does not change hardware volume.
This is provided for convenience -- you can mix your own audio data.
:note: SDL-ctypes doesn't know the current play format, so you must
always pass in byte buffers (SDL_array or sequence) to this function,
rather than of the native data type.
:Parameters:
- `dst`: `SDL_array`
- `src`: `SDL_array`
- `length`: int
- `volume`: int
'''
dstref, dst = array.to_ctypes(dst, len(dst), c_ubyte)
srcref, src = array.to_ctypes(src, len(src), c_ubyte)
if len(dst) < length:
raise TypeError, 'Destination buffer too small'
elif len(src) < length:
raise TypeError, 'Source buffer too small'
_SDL_MixAudio(dst, src, length, volume)
SDL_LockAudio = dll.function('SDL_LockAudio',
'''Guarantee the callback function is not running.
The lock manipulated by these functions protects the callback function.
During a LockAudio/UnlockAudio pair, you can be guaranteed that the
callback function is not running. Do not call these from the callback
function or you will cause deadlock.
''',
args=[],
arg_types=[],
return_type=None)
SDL_UnlockAudio = dll.function('SDL_UnlockAudio',
'''Release the audio callback lock.
:see: `SDL_LockAudio`
''',
args=[],
arg_types=[],
return_type=None)
SDL_CloseAudio = dll.function('SDL_CloseAudio',
'''Shut down audio processing and close the audio device.
''',
args=[],
arg_types=[],
return_type=None)
| Python |
#!/usr/bin/env python
'''Main module for importing SDL-ctypes.
This module defines the intialization and cleanup functions:
- `SDL_Init`
- `SDL_InitSubSystem`
- `SDL_WasInit`
- `SDL_QuitSubSystem`
- `SDL_Quit`
It also imports all functions, constants and classes from the package
submodules. Typical usage, then, is to just import this module directly
into your namespace::
from SDL import *
This gives you access to all SDL names exactly as they appear in the C
header files.
:group Non-core modules: ttf, mixer, image, sound
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import ctypes
import sys
import dll as SDL_dll
from audio import *
from constants import *
from endian import *
from error import *
from rwops import *
from timer import *
# SDL.h
_SDL_Init = SDL_dll.private_function('SDL_Init',
arg_types=[ctypes.c_uint],
return_type=ctypes.c_int)
def SDL_Init(flags):
'''Initialise the SDL library.
This function loads the SDL dynamically linked library and initializes
the subsystems specified by `flags` (and those satisfying dependencies)
Unless the `SDL_INIT_NOPARACHUTE` flag is set, it will install cleanup
signal handlers for some commonly ignored fatal signals (like SIGSEGV).
The following flags are recognised:
- `SDL_INIT_TIMER`
- `SDL_INIT_AUDIO`
- `SDL_INIT_VIDEO`
- `SDL_INIT_CDROM`
- `SDL_INIT_JOYSTICK`
- `SDL_INIT_NOPARACHUTE`
- `SDL_INIT_EVENTTHREAD`
- `SDL_INIT_EVERYTHING`
:Parameters:
- `flags`: int
:rtype: int
:return: undocumented (FIXME)
:see: `SDL_Quit`
'''
if sys.platform == 'darwin' and flags & SDL_INIT_VIDEO:
import cocos.audio.SDL.darwin
cocos.audio.SDL.darwin.init()
return _SDL_Init(flags)
_SDL_InitSubSystem = SDL_dll.private_function('SDL_InitSubSystem',
arg_types=[ctypes.c_uint],
return_type=ctypes.c_int)
def SDL_InitSubSystem(flags):
'''Initialize specific SDL subsystems.
:Parameters:
- `flags`: int
:rtype: int
:return: undocumented (FIXME)
:see: `SDL_Init`, `SDL_QuitSubSystem`
'''
if sys.platform == 'darwin' and flags & SDL_INIT_VIDEO:
import cocos.audio.SDL.darwin
cocos.audio.SDL.darwin.init()
return _SDL_InitSubSystem(flags)
SDL_QuitSubSystem = SDL_dll.function('SDL_QuitSubSystem',
'''Clean up specific SDL subsystems.
:Parameters:
- `flags`: int
:see: `SDL_InitSubSystem`
''',
args=['flags'],
arg_types=[ctypes.c_uint],
return_type=None)
SDL_WasInit = SDL_dll.function('SDL_WasInit',
'''Return a mask of the specified subsystems which have been
initialized.
If `flags` is 0, return a mask of all initialized subsystems.
:Parameters:
- `flags`: int
:rtype: int
:return: undocumented (FIXME)
:see: `SDL_Init`
''',
args=['flags'],
arg_types=[ctypes.c_uint],
return_type=ctypes.c_int)
SDL_Quit = SDL_dll.function('SDL_Quit',
'''Clean up all initialized subsystems.
You should call this function upon all exit conditions.
''',
args=[],
arg_types=[],
return_type=None)
| Python |
#!/usr/bin/env python
'''Error detection and error handling functions.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
import dll
class SDL_Exception(Exception):
'''Exception raised for all SDL errors.
The message is as returned by `SDL_GetError`.
'''
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class SDL_NotImplementedError(NotImplementedError):
'''Exception raised when the available SDL library predates the
requested function.'''
pass
SDL_SetError = dll.function('SDL_SetError',
'''Set the static error string.
:Parameters:
`fmt`
format string; subsequent integer and string arguments are
interpreted as in printf().
''',
args=['fmt'],
arg_types=[c_char_p],
return_type=None)
SDL_GetError = dll.function('SDL_GetError',
'''Return the last error string set.
:rtype: string
''',
args=[],
arg_types=[],
return_type=c_char_p)
SDL_ClearError = dll.function('SDL_ClearError',
'''Clear any error string set.
''',
args=[],
arg_types=[],
return_type=None)
# SDL_Error not implemented (marked private in SDL_error.h)
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
class NoAudioError(Exception):
pass
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""This is a wrapper to the low level music API. You shouldn't use this in
your cocos applications; but instead use the music control functions in the
Scene class
"""
from cocos import audio
try:
import pygame.music
except ImportError:
audio._working = False
class MusicControl(object):
def load(self, filename):
pygame.music.load(filename)
def play(self):
pygame.music.play()
def stop(self):
pygame.music.stop()
class DummyMusicControl(object):
def load(self,filename):
pass
def play(self):
pass
def stop(self):
pass
def set_control(name):
global control
assert name in ('dummy', 'pygame')
control = globals()["_" + name]
_dummy = DummyMusicControl()
_pygame = MusicControl()
set_control('dummy')
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
__docformat__ = 'restructuredtext'
from cocos import audio
try:
from cocos.audio.pygame.mixer import Sound
except ImportError:
audio._working = False
import actions
class Effect(object):
"""Effects are sounds effect loaded in memory
Example ::
shot = Effect('bullet.wav')
shot.play() # Play right now
sprite.do(shot.action)
"""
def __init__(self, filename):
"""Initialize the effect
:Parameters:
`filename` : fullpath
path of a WAV or Ogg audio file
"""
if audio._working:
self.sound = Sound(filename)
else:
self.sound = None
self.action = actions.PlayAction(self.sound)
def play(self):
if audio._working:
self.sound.play()
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
__all__ = ['SDL', 'pygame']
import cocos
_working = True
try:
import pygame.mixer
except ImportError, error:
# set to 0 to debug import errors
if 1:
_working = False
else:
raise
def initialize(arguments={}):
global _working
if arguments is None:
_working = False
music.set_control('dummy')
if _working:
pygame.mixer.init(**arguments)
music.set_control('pygame')
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""
Scene class and subclasses
"""
__docformat__ = 'restructuredtext'
__all__ = ['Scene']
from pyglet.gl import *
import cocos
from cocos.director import director
import cocos.cocosnode as cocosnode
import cocos.audio.music
class EventHandlerMixin(object):
def add(self, child, *args, **kwargs):
super(EventHandlerMixin, self).add(child, *args, **kwargs)
scene = self.get(Scene)
if not scene: return
if ( scene._handlers_enabled and
scene.is_running and
isinstance(child, cocos.layer.Layer)
):
child.push_all_handlers()
def remove(self, child):
super(EventHandlerMixin, self).remove(child)
scene = self.get(Scene)
if not scene: return
if ( scene._handlers_enabled and
scene.is_running and
isinstance(child, cocos.layer.Layer)
):
child.remove_all_handlers()
class Scene(cocosnode.CocosNode, EventHandlerMixin):
"""
"""
def __init__(self, *children):
"""
Creates a Scene with layers and / or scenes.
Responsibilities:
Control the dispatching of events to its layers; and background music playback
:Parameters:
`children` : list of `Layer` or `Scene`
Layers or Scenes that will be part of the scene.
They are automatically assigned a z-level from 0 to
num_children.
"""
super(Scene,self).__init__()
self._handlers_enabled = False
for i, c in enumerate(children):
self.add( c, z=i )
x,y = director.get_window_size()
self.transform_anchor_x = x/2
self.transform_anchor_y = y/2
self.music = None
self.music_playing = False
def on_enter(self):
for c in self.get_children():
c.parent = self
super(Scene, self).on_enter()
if self.music is not None:
cocos.audio.music.control.load(self.music)
if self.music_playing:
cocos.audio.music.control.play()
def on_exit(self):
super(Scene, self).on_exit()
# _apply_music after super, because is_running must be already False
if self.music_playing:
cocos.audio.music.control.stop()
def push_all_handlers(self):
for child in self.get_children():
if isinstance(child, cocos.layer.Layer):
child.push_all_handlers()
def remove_all_handlers(self):
for child in self.get_children():
if isinstance(child, cocos.layer.Layer):
child.remove_all_handlers()
def enable_handlers(self, value=True):
"""
This function makes the scene elegible for receiving events
"""
if value and not self._handlers_enabled and self.is_running:
self.push_all_handlers()
elif not value and self._handlers_enabled and self.is_running:
self.remove_all_handlers()
self._handlers_enabled = value
def end(self, value=None):
"""Ends the current scene setting director.return_value with `value`
:Parameters:
`value` : anything
The return value. It can be anything. A type or an instance.
"""
director.return_value = value
director.pop()
def load_music(self, filename):
"""This prepares a streamed music file to be played in this scene.
Music will be stopped after calling this (even if it was playing before).
:Parameters:
`filename` : fullpath
Filename of music to load.
Depending on installed libraries, supported formats may be
WAV, MP3, OGG, MOD;
You can also use 'None' to unset music
"""
self.music = filename
self.music_playing = False
if self.is_running:
if filename is not None:
cocos.audio.music.control.load(filename)
else:
cocos.audio.music.control.stop()
def play_music(self):
"""Enable music playback for this scene. Nothing happens if music was already playing
Note that if you call this method on an inactive scene, the music will
start playing back only if/when the scene gets activated.
"""
if self.music is not None and not self.music_playing:
self.music_playing = True
if self.is_running:
cocos.audio.music.control.play()
def stop_music(self):
"""Stops music playback for this scene.
"""
self.load_music(None)
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Camera object'''
__docformat__ = 'restructuredtext'
from director import director
from euclid import Point3
from pyglet.gl import *
__all__ = ['Camera']
class Camera(object):
"""
Camera used in every `CocosNode`.
Useful to look at the object from different views.
The OpenGL gluLookAt() function is used to locate the
camera.
If the object is transformed by any of the scale, rotation or
position attributes, then they will override the camera.
"""
def __init__(self):
self.restore()
@classmethod
def get_z_eye( cls ):
'''Returns the best distance for the camera for the current window size
cocos2d uses a Filed Of View (fov) of 60
'''
width, height = director.get_window_size()
eye_z = height / 1.1566
return eye_z
def restore( self ):
'''Restore the camera to the initial position
and sets it's ``dirty`` attribute in False and ``once`` in true.
If you use the camera, for a while and you want to stop using it
call this method.
'''
width, height = director.get_window_size()
# tuple (x,y,z) that says where is the eye of the camera.
# used by ``gluLookAt()``
self._eye = Point3( width /2.0, height /2.0, self.get_z_eye() )
# tuple (x,y,z) that says where is pointing to the camera.
# used by ``gluLookAt()``
self._center = Point3( width /2.0, height /2.0, 0.0 )
# tuple (x,y,z) that says the up vector for the camera.
# used by ``gluLookAt()``
self._up_vector = Point3( 0.0, 1.0, 0.0)
#: whether or not the camera is 'dirty'
#: It is dirty if it is not in the original position
self.dirty = False
#: optimization. Only renders the camera once
self.once = False
def locate( self, force=False ):
'''Sets the camera using gluLookAt using its eye, center and up_vector
:Parameters:
`force` : bool
whether or not the camera will be located even if it is not dirty
'''
if force or self.dirty or self.once:
glLoadIdentity()
gluLookAt( self._eye.x, self._eye.y, self._eye.z, # camera eye
self._center.x, self._center.y, self._center.z, # camera center
self._up_vector.x, self._up_vector.y, self._up_vector.z # camera up vector
)
self.once = False
def _get_eye( self ):
return self._eye
def _set_eye( self, eye ):
self._eye = eye
self.dirty = True
eye = property(_get_eye, _set_eye, doc='''Eye of the camera in x,y,z coordinates
:type: flaat,float,float
''')
def _get_center( self ):
return self._center
def _set_center( self, center ):
self._center = center
self.dirty = True
center = property(_get_center, _set_center, doc='''Center of the camera in x,y,z coordinates
:type: flaat,float,float
''')
def _get_up_vector( self ):
return self._up_vector
def _set_up_vector( self, up_vector ):
self._up_vector = up_vector
self.dirty = True
up_vector = property(_get_up_vector, _set_up_vector, doc='''Up vector of the camera in x,y,z coordinates
:type: flaat,float,float
''')
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from ctypes import *
from pyglet.gl import *
class GLSLException(Exception): pass
def glsl_log(handle):
if handle == 0:
return ''
log_len = c_int(0)
glGetObjectParameterivARB(handle, GL_OBJECT_INFO_LOG_LENGTH_ARB,
byref(log_len))
if log_len.value == 0:
return ''
log = create_string_buffer(log_len.value) # does log_len include the NUL?
chars_written = c_int(0)
glGetInfoLogARB(handle, log_len.value, byref(chars_written), log)
return log.value
class Shader(object):
s_tag = 0
def __init__(self, name, prog):
self.name = name
self.prog = prog
self.shader = 0
self.compiling = False
self.tag = -1
self.dependencies = []
def __del__(self):
self.destroy()
def _source(self):
if self.tag == Shader.s_tag: return []
self.tag = Shader.s_tag
r = []
for d in self.dependencies:
r.extend(d._source())
r.append(self.prog)
return r
def _compile(self):
if self.shader: return
if self.compiling : return
self.compiling = True
self.shader = glCreateShaderObjectARB(self.shaderType())
if self.shader == 0:
raise GLSLException('faled to create shader object')
prog = c_char_p(self.prog)
length = c_int(-1)
glShaderSourceARB(self.shader,
1,
cast(byref(prog), POINTER(POINTER(c_char))),
byref(length))
glCompileShaderARB(self.shader)
self.compiling = False
compile_status = c_int(0)
glGetObjectParameterivARB(self.shader, GL_OBJECT_COMPILE_STATUS_ARB, byref(compile_status))
if not compile_status.value:
err = glsl_log(self.shader)
glDeleteObjectARB(self.shader)
self.shader = 0
raise GLSLException('failed to compile shader', err)
def _attachTo(self, program):
if self.tag == Shader.s_tag: return
self.tag = Shader.s_tag
for d in self.dependencies:
d._attachTo(program)
if self.isCompiled():
glAttachObjectARB(program, self.shader)
def addDependency(self, shader):
self.dependencies.append(shader)
return self
def destroy(self):
if self.shader != 0: glDeleteObjectARB(self.shader)
def shaderType(self):
raise NotImplementedError()
def isCompiled(self):
return self.shader != 0
def attachTo(self, program):
Shader.s_tag = Shader.s_tag + 1
self._attachTo(program)
# ATI/apple's glsl compiler is broken.
def attachFlat(self, program):
if self.isCompiled():
glAttachObjectARB(program, self.shader)
def compileFlat(self):
if self.isCompiled(): return
self.shader = glCreateShaderObjectARB(self.shaderType())
if self.shader == 0:
raise GLSLException('faled to create shader object')
all_source = ['\n'.join(self._source())]
prog = (c_char_p * len(all_source))(*all_source)
length = (c_int * len(all_source))(-1)
glShaderSourceARB(self.shader,
len(all_source),
cast(prog, POINTER(POINTER(c_char))),
length)
glCompileShaderARB(self.shader)
compile_status = c_int(0)
glGetObjectParameterivARB(self.shader, GL_OBJECT_COMPILE_STATUS_ARB, byref(compile_status))
if not compile_status.value:
err = glsl_log(self.shader)
glDeleteObjectARB(self.shader)
self.shader = 0
raise GLSLException('failed to compile shader', err)
def compile(self):
if self.isCompiled(): return
for d in self.dependencies:
d.compile()
self._compile()
class VertexShader(Shader):
def shaderType(self): return GL_VERTEX_SHADER_ARB
class FragmentShader(Shader):
def shaderType(self): return GL_FRAGMENT_SHADER_ARB
class ShaderProgram(object):
def __init__(self, vertex_shader=None, fragment_shader=None):
self.vertex_shader = vertex_shader
self.fragment_shader = fragment_shader
self.program = 0
def __del__(self):
self.destroy()
def destroy(self):
if self.program != 0: glDeleteObjectARB(self.program)
def setShader(self, shader):
if isinstance(shader, FragmentShader):
self.fragment_shader = shader
if isinstance(shader, VertexShader):
self.vertex_shader = shader
if self.program != 0: glDeleteObjectARB(self.program)
def link(self):
if self.vertex_shader is not None: self.vertex_shader.compileFlat()
if self.fragment_shader is not None: self.fragment_shader.compileFlat()
self.program = glCreateProgramObjectARB()
if self.program == 0:
raise GLSLException('failed to create program object')
if self.vertex_shader is not None: self.vertex_shader.attachFlat(self.program)
if self.fragment_shader is not None: self.fragment_shader.attachFlat(self.program)
glLinkProgramARB(self.program)
link_status = c_int(0)
glGetObjectParameterivARB(self.program, GL_OBJECT_LINK_STATUS_ARB, byref(link_status))
if link_status.value == 0:
err = glsl_log(self.program)
glDeleteObjectARB(self.program)
self.program = 0
raise GLSLException('failed to link shader', err)
self.__class__._uloc_ = {}
self.__class__._vloc_ = {}
return self.program
def prog(self):
if self.program: return self.program
return self.link()
def install(self):
p = self.prog()
if p != 0:
glUseProgramObjectARB(p)
def uninstall(self):
glUseProgramObjectARB(0)
def uniformLoc(self, var):
try:
return self.__class__._uloc_[var]
except:
if self.program == 0:
self.link()
self.__class__._uloc_[var] = v = glGetUniformLocationARB(self.program, var)
return v
def uset1F(self, var, x):
glUniform1fARB(self.uniformLoc(var), x)
def uset2F(self, var, x, y):
glUniform2fARB(self.uniformLoc(var), x, y)
def uset3F(self, var, x, y, z):
glUniform3fARB(self.uniformLoc(var), x, y, z)
def uset4F(self, var, x, y, z, w):
glUniform4fARB(self.uniformLoc(var), x, y, z, w)
def uset1I(self, var, x):
glUniform1iARB(self.uniformLoc(var), x)
def uset3I(self, var, x, y, z):
glUniform1iARB(self.uniformLoc(var), x, y, z)
def usetM4F(self, var, m):
pass
# glUniform1iARB(self.uniformLoc(var), x, y, z)
def usetTex(self, var, u, v):
glUniform1iARB(self.uniformLoc(var), u)
glActiveTexture(GL_TEXTURE0 + u)
glBindTexture(v.gl_tgt, v.gl_id)
__all__ = ['VertexShader', 'FragmentShader', 'ShaderProgram', 'GLSLException']
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""A thin wrapper for OpenGL framebuffer objets. For implementation use only"""
__docformat__ = 'restructuredtext'
from pyglet.gl import *
class FramebufferObject (object):
"""
Wrapper for framebuffer objects. See
http://oss.sgi.com/projects/ogl-sample/registry/EXT/framebuffer_object.txt
API is not very OO, should be improved.
"""
def __init__ (self):
"""Create a new framebuffer object"""
id = GLuint(0)
glGenFramebuffersEXT (1, byref(id))
self._id = id.value
def bind (self):
"""Set FBO as current rendering target"""
glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, self._id)
def unbind (self):
"""Set default framebuffer as current rendering target"""
glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, 0)
def texture2d (self, texture):
"""Map currently bound framebuffer (not necessarily self) to texture"""
glFramebufferTexture2DEXT (
GL_FRAMEBUFFER_EXT,
GL_COLOR_ATTACHMENT0_EXT,
texture.target,
texture.id,
texture.level)
def check_status(self):
"""Check that currently set framebuffer is ready for rendering"""
status = glCheckFramebufferStatusEXT (GL_FRAMEBUFFER_EXT)
if status != GL_FRAMEBUFFER_COMPLETE_EXT:
raise Exception ("Frambuffer not complete: %d" % status)
def __del__(self):
'''Delete the framebuffer from the GPU memory'''
id = GLuint(self._id)
glDeleteFramebuffersEXT(1, byref(id))
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''This module defines the ScrollableLayer and ScrollingManager classes.
Controlling Scrolling
---------------------
You have two options for scrolling:
1. automatically scroll the map but stop at the map edges, and
2. scroll the map an allow the edge of the map to be displayed.
The ScrollingManager has a concept of "focus" which is the pixel
position of the player's view focus (*usually* the center of the
player sprite itself, but the player may be allowed to
move the view around, or you may move it around for them to highlight
something else in the scene). The ScrollingManager is clever enough to
manage many layers and handle scaling them.
Two methods are available for setting the map focus:
**set_focus(x, y)**
Attempt to set the focus to the pixel coordinates given. The layer(s)
contained in the ScrollingManager are moved accordingly. If a layer
would be moved outside of its define px_width, px_height then the
scrolling is restricted. The resultant restricted focal point is stored
on the ScrollingManager as restricted_fx and restricted_fy.
**force_focus(x, y)**
Force setting the focus to the pixel coordinates given. The layer(s)
contained in the ScrollingManager are moved accordingly regardless of
whether any out-of-bounds cells would be displayed. The .fx and .fy
attributes are still set, but they'll *always* be set to the supplied
x and y values.
'''
__docformat__ = 'restructuredtext'
from cocos.director import director
from cocos.layer.base_layers import Layer
import pyglet
from pyglet.gl import *
class ScrollableLayer(Layer):
'''A Cocos Layer that is scrollable in a Scene.
A layer may have a "parallax" value which is used to scale the position
(and not the dimensions) of the view of the layer - the layer's view
(x, y) coordinates are calculated as::
my_view_x = parallax * passed_view_x
my_view_y = parallax * passed_view_y
Scrollable layers have a view which identifies the section of the layer
currently visible.
The scrolling is usually managed by a ScrollingManager.
'''
view_x, view_y = 0, 0
view_w, view_h = 0, 0
origin_x = origin_y = origin_z = 0
def __init__(self, parallax=1):
super(ScrollableLayer,self).__init__()
self.parallax = parallax
# force (cocos) transform anchor to be 0 so we don't OpenGL
# glTranslate() and screw up our pixel alignment on screen
self.transform_anchor_x = 0
self.transform_anchor_y = 0
# XXX batch eh?
self.batch = pyglet.graphics.Batch()
def on_enter(self):
director.push_handlers(self.on_cocos_resize)
super(ScrollableLayer, self).on_enter()
def set_view(self, x, y, w, h, viewport_ox=0, viewport_oy=0):
x *= self.parallax
y *= self.parallax
self.view_x, self.view_y = x, y
self.view_w, self.view_h = w, h
#print 'ScrollableLayer view - x, y, w, h:', self.view_x, self.view_y, self.view_w, self.view_h
x -= self.origin_x
y -= self.origin_y
x -= viewport_ox
y -= viewport_oy
self.position = (-x, -y)
def draw(self):
# invoked by Cocos machinery
super(ScrollableLayer, self).draw()
# XXX overriding draw eh?
glPushMatrix()
self.transform()
self.batch.draw()
glPopMatrix()
def set_dirty(self):
'''The viewport has changed in some way.
'''
pass
def on_cocos_resize(self, usable_width, usable_height):
self.set_dirty()
class ScrollingManager(Layer):
'''Manages scrolling of Layers in a Cocos Scene.
Each ScrollableLayer that is added to this manager (via standard list
methods) may have pixel dimensions .px_width and .px_height. Tile
module MapLayers have these attribtues. The manager will limit scrolling
to stay within the pixel boundary of the most limiting layer.
If a layer has no dimensions it will scroll freely and without bound.
The manager is initialised with the viewport (usually a Window) which has
the pixel dimensions .width and .height which are used during focusing.
A ScrollingManager knows how to convert pixel coordinates from its own
pixel space to the screen space.
'''
def __init__(self, viewport=None, do_not_scale=None):
if do_not_scale is None:
do_not_scale = director.do_not_scale_window
self.autoscale = not do_not_scale and not director.do_not_scale_window
self.viewport = viewport
# These variables define the Layer-space pixel view which is mapping
# to the viewport. If the Layer is not scrolled or scaled then this
# will be a one to one mapping.
self.view_x, self.view_y = 0, 0
self.view_w, self.view_h = 1, 1
self.childs_ox = 0
self.childs_oy = 0
# Focal point on the Layer
self.fx = self.fy = 0
super(ScrollingManager, self).__init__()
# always transform about 0,0
self.transform_anchor_x = 0
self.transform_anchor_y = 0
def on_enter(self):
super(ScrollingManager, self).on_enter()
director.push_handlers(self.on_cocos_resize)
self.update_view_size()
self.refresh_focus()
def update_view_size(self):
if self.viewport is not None:
self.view_w, self.view_h = self.viewport.width, self.viewport.height
self.view_x, self.view_y = getattr(self.viewport, 'position', (0,0))
if director.do_not_scale_window:
self._scissor_flat = (self.view_x, self.view_y,
self.view_w, self.view_h)
else:
w, h = director.get_window_size()
sx = director._usable_width/float(w)
sy = director._usable_height/float(h)
self._scissor_flat = (int(self.view_x * sx), int(self.view_y * sy),
int(self.view_w * sx), int(self.view_h * sy))
elif self.autoscale:
self.view_w, self.view_h = director.get_window_size()
else:
self.view_w = director._usable_width
self.view_h = director._usable_height
def on_cocos_resize(self, usable_width, usable_height):
# when using an explicit viewport you should adjust the viewport for
# resize changes here, before the lines that follows.
# Also, if your app performs other changes in viewport it should
# use the lines that follows to update viewport-related internal state
self.update_view_size()
self.refresh_focus()
def refresh_focus(self):
if self.children:
self._old_focus = None # disable NOP check
self.set_focus(self.fx, self.fy)
_scale = 1.0
def set_scale(self, scale):
self._scale = 1.0*scale
self.refresh_focus()
scale = property(lambda s: s._scale, set_scale)
def add(self, child, z=0, name=None):
'''Add the child and then update the manager's focus / viewport.
'''
super(ScrollingManager, self).add(child, z=z, name=name)
# set the focus again and force it so we don't just skip because the
# focal point hasn't changed
self.set_focus(self.fx, self.fy, force=True)
def pixel_from_screen(self, x, y):
'''Look up the Layer-space pixel matching the screen-space pixel.
Account for viewport, layer and screen transformations.
'''
# director display scaling
if not director.do_not_scale_window:
x, y = director.get_virtual_coordinates(x, y)
# normalise x,y coord
ww, wh = director.get_window_size()
sx = x / float(self.view_w)
sy = y / float(self.view_h)
# get the map-space dimensions
vx, vy = self.childs_ox, self.childs_oy
# get our scaled view size
w = int(self.view_w / self.scale)
h = int(self.view_h / self.scale)
#print (int(x), int(y)), (vx, vy, w, h), int(vx + sx * w), int(vy + sy * h)
# convert screen pixel to map pixel
return int(vx + sx * w), int(vy + sy * h)
def pixel_to_screen(self, x, y):
'''Look up the screen-space pixel matching the Layer-space pixel.
Account for viewport, layer and screen transformations.
'''
screen_x = self.scale*(x-self.childs_ox)
screen_y = self.scale*(y-self.childs_oy)
return int(screen_x), int(screen_y)
_old_focus = None
def set_focus(self, fx, fy, force=False):
'''Determine the viewport based on a desired focus pixel in the
Layer space (fx, fy) and honoring any bounding restrictions of
child layers.
The focus will always be shifted to ensure no child layers display
out-of-bounds data, as defined by their dimensions px_width and px_height.
'''
# if no child specifies dimensions then just force the focus
if not [l for z,l in self.children if hasattr(l, 'px_width')]:
return self.force_focus(fx, fy)
# This calculation takes into account the scaling of this Layer (and
# therefore also its children).
# The result is that all chilren will have their viewport set, defining
# which of their pixels should be visible.
fx, fy = int(fx), int(fy)
self.fx, self.fy = fx, fy
a = (fx, fy, self.scale)
# check for NOOP (same arg passed in)
if not force and self._old_focus == a:
return
self._old_focus = a
# collate children dimensions
x1 = []; y1 = []; x2 = []; y2 = []
for z, layer in self.children:
if not hasattr(layer, 'px_width'): continue
x1.append(layer.origin_x)
y1.append(layer.origin_y)
x2.append(layer.origin_x + layer.px_width)
y2.append(layer.origin_y + layer.px_height)
# figure the child layer min/max bounds
b_min_x = min(x1)
b_min_y = min(y1)
b_max_x = min(x2)
b_max_y = min(y2)
# get our viewport information, scaled as appropriate
w = int(self.view_w / self.scale)
h = int(self.view_h / self.scale)
w2, h2 = w//2, h//2
if (b_max_x - b_min_x)<=w:
# this branch for prety centered view and no view jump when
# crossing the center; both when world width <= view width
restricted_fx = (b_max_x + b_min_x)/2
else:
if (fx - w2) < b_min_x:
restricted_fx = b_min_x + w2 # hit minimum X extent
elif (fx + w2) > b_max_x:
restricted_fx = b_max_x - w2 # hit maximum X extent
else:
restricted_fx = fx
if (b_max_y - b_min_y)<=h:
# this branch for prety centered view and no view jump when
# crossing the center; both when world height <= view height
restricted_fy = (b_max_y + b_min_y)/2
else:
if (fy - h2) < b_min_y:
restricted_fy = b_min_y + h2 # hit minimum Y extent
elif (fy + h2) > b_max_y:
restricted_fy = b_max_y - h2 # hit maximum Y extent
else:
restricted_fy = fy
# ... and this is our focus point, center of screen
self.restricted_fx = int(restricted_fx)
self.restricted_fy = int(restricted_fy)
# determine child view bounds to match that focus point
x, y = int(restricted_fx - w2), int(restricted_fy - h2)
childs_scroll_x = x #- self.view_x/self.scale
childs_scroll_y = y #- self.view_y/self.scale
self.childs_ox = childs_scroll_x - self.view_x/self.scale
self.childs_oy = childs_scroll_y - self.view_y/self.scale
for z, layer in self.children:
layer.set_view(childs_scroll_x, childs_scroll_y, w, h,
self.view_x/self.scale, self.view_y/self.scale)
def force_focus(self, fx, fy):
'''Force the manager to focus on a point, regardless of any managed layer
visible boundaries.
'''
# This calculation takes into account the scaling of this Layer (and
# therefore also its children).
# The result is that all chilren will have their viewport set, defining
# which of their pixels should be visible.
self.fx, self.fy = map(int, (fx, fy))
self.fx, self.fy = fx, fy
# get our scaled view size
w = int(self.view_w / self.scale)
h = int(self.view_h / self.scale)
w2, h2 = w//2, h//2
# bottom-left corner of the
x, y = fx - w2, fy - h2
childs_scroll_x = x #- self.view_x/self.scale
childs_scroll_y = y #- self.view_y/self.scale
self.childs_ox = childs_scroll_x - self.view_x/self.scale
self.childs_oy = childs_scroll_y - self.view_y/self.scale
for z, layer in self.children:
layer.set_view(childs_scroll_x, childs_scroll_y, w, h,
self.view_x/self.scale, self.view_y/self.scale)
def set_state(self):
# preserve gl scissors info
self._scissor_enabled = glIsEnabled(GL_SCISSOR_TEST)
self._old_scissor_flat = (GLint * 4)() #4-tuple
glGetIntegerv(GL_SCISSOR_BOX, self._old_scissor_flat)
# set our scissor
if not self._scissor_enabled:
glEnable(GL_SCISSOR_TEST)
glScissor(*self._scissor_flat)
def unset_state(self):
# restore gl scissors info
glScissor(*self._old_scissor_flat)
if not self._scissor_enabled:
glDisable(GL_SCISSOR_TEST)
def visit(self):
if self.viewport is not None:
self.set_state()
super(ScrollingManager, self).visit()
self.unset_state()
else:
super(ScrollingManager, self).visit()
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
#
# Python Interpreter
# 95% of the code from 'Bruce: the presentation tool' by Richard Jones
# http://code.google.com/p/bruce-tpt/
#
#
__docformat__ = 'restructuredtext'
import sys
import os
import code
import pyglet
from pyglet import graphics
from pyglet import text
from pyglet.text import caret, document, layout
import cocos
from cocos.director import director
from base_layers import Layer
from util_layers import ColorLayer
__all__ = ['PythonInterpreterLayer']
class Output:
def __init__(self, display, realstdout):
self.out = display
self.realstdout = realstdout
self.data = ''
def write(self, data):
self.out(data)
class MyInterpreter(code.InteractiveInterpreter):
def __init__(self, locals, display):
self.write = display
code.InteractiveInterpreter.__init__(self, locals=locals)
def execute(self, input):
old_stdout = sys.stdout
sys.stdout = Output(self.write, old_stdout)
more = self.runsource(input)
sys.stdout = old_stdout
return more
class PythonInterpreterLayer(ColorLayer):
'''Runs an interactive Python interpreter as a child `Layer` of the current `Scene`.
'''
cfg = {'code.font_name':'Arial',
'code.font_size':12,
'code.color':(255,255,255,255),
'caret.color':(255,255,255),
}
name = 'py'
prompt = ">>> " #: python prompt
prompt_more = "... " #: python 'more' prompt
doing_more = False
is_event_handler = True #: enable pyglet's events
def __init__(self):
super(PythonInterpreterLayer, self).__init__( 32,32,32,192 )
self.content = self.prompt
local_vars = director.interpreter_locals
local_vars["self"] = self
self.interpreter = MyInterpreter(
local_vars, self._write)
self.current_input = []
self.history = ['']
self.history_pos = 0
def on_enter(self):
super(PythonInterpreterLayer, self).on_enter()
vw,vh = cocos.director.director.get_window_size()
# format the code
self.document = document.FormattedDocument(self.content)
self.document.set_style(0, len(self.document.text), {
'font_name': self.cfg['code.font_name'],
'font_size': self.cfg['code.font_size'],
'color': self.cfg['code.color'],
})
self.batch = graphics.Batch()
# generate the document
self.layout = layout.IncrementalTextLayout(self.document,
vw, vh, multiline=True, batch=self.batch)
self.layout.anchor_y= 'top'
self.caret = caret.Caret(self.layout, color=self.cfg['caret.color'] )
self.caret.on_activate()
self.on_resize(vw, vh)
self.start_of_line = len(self.document.text)
def on_resize(self, x, y):
vw, vh = director.get_window_size()
self.layout.begin_update()
self.layout.height = vh
self.layout.x = 2
self.layout.width = vw - 4
self.layout.y = vh
self.layout.end_update()
# XXX: hack
x,y = director.window.width, director.window.height
self.layout.top_group._scissor_width=x-4
self.caret.position = len(self.document.text)
def on_exit(self):
super(PythonInterpreterLayer, self).on_exit()
self.content = self.document.text
self.document = None
self.layout = None
self.batch = None
self.caret = None
def on_key_press(self, symbol, modifiers):
if symbol == pyglet.window.key.TAB:
return self.caret.on_text('\t')
elif symbol in (pyglet.window.key.ENTER, pyglet.window.key.NUM_ENTER):
# write the newline
self._write('\n')
line = self.document.text[self.start_of_line:]
if line.strip() == 'help()':
line = 'print "help() not supported, sorry!"'
self.current_input.append(line)
self.history_pos = len(self.history)
if line.strip():
self.history[self.history_pos-1] = line.strip()
self.history.append('')
more = False
if not self.doing_more:
more = self.interpreter.execute('\n'.join(self.current_input))
if self.doing_more and not line.strip():
self.doing_more = False
self.interpreter.execute('\n'.join(self.current_input))
more = more or self.doing_more
if not more:
self.current_input = []
self._write(self.prompt)
else:
self.doing_more = True
self._write(self.prompt_more)
self.start_of_line = len(self.document.text)
self.caret.position = len(self.document.text)
elif symbol == pyglet.window.key.SPACE:
pass
else:
return pyglet.event.EVENT_UNHANDLED
return pyglet.event.EVENT_HANDLED
def on_text(self, symbol):
# squash carriage return - we already handle them above
if symbol == '\r':
return pyglet.event.EVENT_HANDLED
self._scroll_to_bottom()
return self.caret.on_text(symbol)
def on_text_motion(self, motion):
at_sol = self.caret.position == self.start_of_line
if motion == pyglet.window.key.MOTION_UP:
# move backward in history, storing the current line of input
# if we're at the very end of time
line = self.document.text[self.start_of_line:]
if self.history_pos == len(self.history)-1:
self.history[self.history_pos] = line
self.history_pos = max(0, self.history_pos-1)
self.document.delete_text(self.start_of_line,
len(self.document.text))
self._write(self.history[self.history_pos])
self.caret.position = len(self.document.text)
elif motion == pyglet.window.key.MOTION_DOWN:
# move forward in the history
self.history_pos = min(len(self.history)-1, self.history_pos+1)
self.document.delete_text(self.start_of_line,
len(self.document.text))
self._write(self.history[self.history_pos])
self.caret.position = len(self.document.text)
elif motion == pyglet.window.key.MOTION_BACKSPACE:
# can't delete the prompt
if not at_sol:
return self.caret.on_text_motion(motion)
elif motion == pyglet.window.key.MOTION_LEFT:
# can't move back beyond start of line
if not at_sol:
return self.caret.on_text_motion(motion)
elif motion == pyglet.window.key.MOTION_PREVIOUS_WORD:
# can't move back word beyond start of line
if not at_sol:
return self.caret.on_text_motion(motion)
else:
return self.caret.on_text_motion(motion)
return pyglet.event.EVENT_HANDLED
def _write(self, s):
self.document.insert_text(len(self.document.text), s, {
'font_name': self.cfg['code.font_name'],
'font_size': self.cfg['code.font_size'],
'color': self.cfg['code.color'],
})
self._scroll_to_bottom()
def _scroll_to_bottom(self):
# on key press always move the view to the bottom of the screen
if self.layout.height < self.layout.content_height:
self.layout.anchor_y= 'bottom'
self.layout.y = 0
self.layout.view_y = 0
if self.caret.position < self.start_of_line:
self.caret.position = len(self.document.text)
def draw(self):
super( PythonInterpreterLayer, self).draw()
self.batch.draw()
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Layer class and subclasses
A `Layer` has as size the whole drawable area (window or screen),
and knows how to draw itself. It can be semi transparent (having holes
and/or partial transparency in some/all places), allowing to see other layers
behind it. Layers are the ones defining appearance and behavior, so most
of your programming time will be spent coding Layer subclasses that do what
you need. The layer is where you define event handlers.
Events are propagated to layers (from front to back) until some layer catches
the event and accepts it.
"""
__docformat__ = 'restructuredtext'
import pyglet
from pyglet.gl import *
from cocos.director import *
from base_layers import Layer
import cocos.cocosnode
__all__ = ['ColorLayer']
class ColorLayer(Layer):
"""Creates a layer of a certain color.
The color shall be specified in the format (r,g,b,a).
For example, to create green layer::
l = ColorLayer(0, 255, 0, 0 )
The size and position can be changed, for example::
l = ColorLayer( 0, 255,0,0, width=200, height=400)
l.position = (50,50)
"""
def __init__(self, r,g,b,a, width=None, height=None):
super(ColorLayer, self).__init__()
self._batch = pyglet.graphics.Batch()
self._vertex_list = None
self._rgb = r,g,b
self._opacity = a
self.width = width
self.height = height
w,h = director.get_window_size()
if not self.width:
self.width = w
if not self.height:
self.height = h
def on_enter(self):
super(ColorLayer, self).on_enter()
x, y = self.width, self.height
ox, oy = 0, 0
self._vertex_list = self._batch.add(4, pyglet.gl.GL_QUADS, None,
('v2i', ( ox, oy,
ox, oy + y,
ox+x, oy+y,
ox+x, oy)),
'c4B')
self._update_color()
def on_exit(self):
super(ColorLayer, self).on_exit()
self._vertex_list.delete()
self._vertex_list = None
def draw(self):
super(ColorLayer, self).draw()
glPushMatrix()
self.transform()
glPushAttrib(GL_CURRENT_BIT)
self._batch.draw()
glPopAttrib()
glPopMatrix()
def _update_color(self):
if self._vertex_list:
r, g, b = self._rgb
self._vertex_list.colors[:] = [r, g, b, int(self._opacity)] * 4
def _set_opacity(self, opacity):
self._opacity = opacity
self._update_color()
opacity = property(lambda self: self._opacity, _set_opacity,
doc='''Blend opacity.
This property sets the alpha component of the colour of the layer's
vertices. This allows the layer to be drawn with fractional opacity,
blending with the background.
An opacity of 255 (the default) has no effect. An opacity of 128 will
make the sprite appear translucent.
:type: int
''')
def _set_color(self, rgb):
self._rgb = map(int, rgb)
self._update_color()
color = property(lambda self: self._rgb, _set_color,
doc='''Blend color.
This property sets the color of the layer's vertices. This allows the
layer to be drawn with a color tint.
The color is specified as an RGB tuple of integers ``(red, green, blue)``.
Each color component must be in the range 0 (dark) to 255 (saturated).
:type: (int, int, int)
''')
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from base_layers import *
from util_layers import *
from python_interpreter import *
from scrolling import *
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Layer class and subclasses
A `Layer` has as size the whole drawable area (window or screen),
and knows how to draw itself. It can be semi transparent (having holes
and/or partial transparency in some/all places), allowing to see other layers
behind it. Layers are the ones defining appearance and behavior, so most
of your programming time will be spent coding Layer subclasses that do what
you need. The layer is where you define event handlers.
Events are propagated to layers (from front to back) until some layer catches
the event and accepts it.
"""
__docformat__ = 'restructuredtext'
from cocos.director import *
from cocos import cocosnode
from cocos import scene
__all__ = [ 'Layer', 'MultiplexLayer']
class Layer(cocosnode.CocosNode, scene.EventHandlerMixin):
"""a CocosNode that automatically handles listening to director.window events"""
#: if True the layer will listen to director.window events
#: Default: False
is_event_handler = False #: if true, the event handlers of this layer will be registered. defaults to false.
def __init__( self ):
super( Layer, self ).__init__()
self.scheduled_layer = False
x,y = director.get_window_size()
self.transform_anchor_x = x/2
self.transform_anchor_y = y/2
def push_all_handlers(self):
""" registers itself to receive director.window events and propagates
the call to childs that are layers.
class member is_event_handler must be True for this to work"""
if self.is_event_handler:
director.window.push_handlers( self )
for child in self.get_children():
if isinstance(child, Layer):
child.push_all_handlers()
def remove_all_handlers(self):
""" de-registers itself to receive director.window events and propagates
the call to childs that are layers.
class member is_event_handler must be True for this to work"""
if self.is_event_handler:
director.window.remove_handlers( self )
for child in self.get_children():
if isinstance(child, Layer):
child.remove_all_handlers()
def on_enter(self):
super(Layer, self).on_enter()
scn = self.get_ancestor(scene.Scene)
if not scn: return
if scn._handlers_enabled:
if self.is_event_handler:
director.window.push_handlers( self )
def on_exit(self):
super(Layer, self).on_exit()
scn = self.get_ancestor(scene.Scene)
if not scn: return
if scn._handlers_enabled:
if self.is_event_handler:
director.window.remove_handlers( self )
#
# MultiplexLayer
class MultiplexLayer( Layer ):
"""A Composite layer that only enables one layer at the time.
This is useful, for example, when you have 3 or 4 menus, but you want to
show one at the time"""
def __init__( self, *layers ):
super( MultiplexLayer, self ).__init__()
self.layers = layers
self.enabled_layer = 0
self.add( self.layers[ self.enabled_layer ] )
def switch_to( self, layer_number ):
"""Switches to another Layer that belongs to the Multiplexor.
:Parameters:
`layer_number` : Integer
MUST be a number between 0 and the quantities of layers - 1.
The running layer will receive an "on_exit()" call, and the
new layer will receive an "on_enter()" call.
"""
if layer_number < 0 or layer_number >= len( self.layers ):
raise Exception("Multiplexlayer: Invalid layer number")
# remove
self.remove( self.layers[ self.enabled_layer ] )
self.enabled_layer = layer_number
self.add( self.layers[ self.enabled_layer ] )
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Singleton that handles the logic behind the Scenes
director
========
Initializing
------------
The director is the singleton that creates and handles the main ``Window``
and manages the logic behind the ``Scenes``.
The first thing to do, is to initialize the ``director``::
from cocos.director import *
director.init( list_of_arguments )
This will initialize the director, and will create a display area
(a 640x480 window by default).
The parameters that are supported by director.init() are the same
parameters that are supported by pyglet.window.Window(), plus a few
cocos exclusive ones.
director.init cocos exclusive parameters:
* ``do_not_scale``: Boleean. Defaults to False, when your app can think
that the windows size dont change despite resize events.
When True, your app must include logic to deal with diferent window
sizes along the session.
* ``audio_backend``: one in ['pyglet','sdl']. Defaults to 'pyglet' for
legacy support.
* ``audio``: None or a dict providing parameters for the sdl audio backend.
* None: in this case a "null" audio system will be used, where all the
sdl sound operations will be no-ops. This may be useful if you do not
want to depend on SDL_mixer
* A dictionary with string keys; these are the arguments for setting up
the audio output (sample rate and bit-width, channels, buffer size).
The key names/values should match the positional arguments of
http://www.pygame.org/docs/ref/mixer.html#pygame.mixer.init
* The default value is {}, which means sound enabled with default
settings
director.init parameters passes to pyglet.window.Window (partial list):
* ``fullscreen``: Boolean. Window is created in fullscreen. Default is False
* ``resizable``: Boolean. Window is resizable. Default is False
* ``vsync``: Boolean. Sync with the vertical retrace. Default is True
* ``width``: Integer. Window width size. Default is 640
* ``height``: Integer. Window height size. Default is 480
* ``caption``: String. Window title.
* ``visible``: Boolean. Window is visible or not. Default is True.
The full list of valid video arguments can be found at the pyglet Window
documentation:
- http://www.pyglet.org/doc/1.1/api/pyglet.window.Window-class.html
Example::
director.init( caption="Hello World", fullscreen=True )
Running a Scene
----------------
Once you have initialized the director, you can run your first ``Scene``::
director.run( Scene( MyLayer() ) )
This will run a scene that has only 1 layer: ``MyLayer()``. You can run a scene
that has multiple layers. For more information about ``Layers`` and ``Scenes``
refer to the ``Layers`` and ``Scene`` documentation.
`cocos.director.Director`
Once a scene is running you can do the following actions:
* ``director.replace( new_scene ):``
Replaces the running scene with the new_scene
You could also use a transition. For example:
director.replace( SplitRowsTransition( new_scene, duration=2 ) )
* ``director.push( new_scene ):``
The running scene will be pushed to a queue of scenes to run,
and new_scene will be executed.
* ``director.pop():``
Will pop out a scene from the queue, and it will replace the running scene.
* ``director.scene.end( end_value ):``
Finishes the current scene with an end value of ``end_value``. The next scene
to be run will be popped from the queue.
Other functions you can use are:
* ``director.get_window_size():``
Returns an (x,y) pair with the _logical_ dimensions of the display.
The display might have been resized, but coordinates are always relative
to this size. If you need the _physical_ dimensions, check the dimensions
of ``director.window``
* ``get_virtual_coordinates(self, x, y):``
Transforms coordinates that belongs the real (physical) window size, to
the coordinates that belongs to the virtual (logical) window. Returns
an x,y pair in logical coordinates.
The director also has some useful attributes:
* ``director.return_value``: The value returned by the last scene that
called ``director.scene.end``. This is useful to use scenes somewhat like
function calls: you push a scene to call it, and check the return value
when the director returns control to you.
* ``director.window``: This is the pyglet window handled by this director,
if you happen to need low level access to it.
* ``self.show_FPS``: You can set this to a boolean value to enable, disable
the framerate indicator.
* ``self.scene``: The scene currently active
'''
__docformat__ = 'restructuredtext'
import sys
from os import getenv
import pyglet
from pyglet import window, event
from pyglet import clock
#from pyglet import media
from pyglet.gl import *
import cocos, cocos.audio
if hasattr(sys, 'is_epydoc') and sys.is_epydoc:
__all__ = ['director', 'Director', 'DefaultHandler']
else:
__all__ = ['director', 'DefaultHandler']
class DefaultHandler( object ):
def __init__(self):
super(DefaultHandler,self).__init__()
self.wired = False
def on_key_press( self, symbol, modifiers ):
if symbol == pyglet.window.key.F and (modifiers & pyglet.window.key.MOD_ACCEL):
director.window.set_fullscreen( not director.window.fullscreen )
return True
elif symbol == pyglet.window.key.P and (modifiers & pyglet.window.key.MOD_ACCEL):
import scenes.pause as pause
pause_sc = pause.get_pause_scene()
if pause:
director.push( pause_sc )
return True
elif symbol == pyglet.window.key.W and (modifiers & pyglet.window.key.MOD_ACCEL):
# import wired
if self.wired == False:
glDisable(GL_TEXTURE_2D);
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);
# wired.wired.install()
# wired.wired.uset4F('color', 1.0, 1.0, 1.0, 1.0 )
self.wired = True
else:
glEnable(GL_TEXTURE_2D);
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);
self.wired = False
# wired.wired.uninstall()
return True
elif symbol == pyglet.window.key.X and (modifiers & pyglet.window.key.MOD_ACCEL):
director.show_FPS = not director.show_FPS
return True
elif symbol == pyglet.window.key.I and (modifiers & pyglet.window.key.MOD_ACCEL):
from layer import PythonInterpreterLayer
if not director.show_interpreter:
if director.python_interpreter == None:
director.python_interpreter = cocos.scene.Scene( PythonInterpreterLayer() )
director.python_interpreter.enable_handlers( True )
director.python_interpreter.on_enter()
director.show_interpreter = True
else:
director.python_interpreter.on_exit()
director.show_interpreter= False
return True
elif symbol == pyglet.window.key.S and (modifiers & pyglet.window.key.MOD_ACCEL):
import time
pyglet.image.get_buffer_manager().get_color_buffer().save('screenshot-%d.png' % (int( time.time() ) ) )
return True
if symbol == pyglet.window.key.ESCAPE:
director.pop()
return True
class ScreenReaderClock(pyglet.clock.Clock):
''' Make frames happen every 1/framerate and takes screenshots '''
def __init__(self, framerate, template, duration):
super(ScreenReaderClock, self).__init__()
self.framerate = framerate
self.template = template
self.duration = duration
self.frameno = 0
self.fake_time = 0
def tick(self, poll=False):
'''Signify that one frame has passed.
'''
# take screenshot
pyglet.image.get_buffer_manager().get_color_buffer().save(self.template % (self.frameno) )
self.frameno += 1
# end?
if self.duration:
if self.fake_time > self.duration:
raise SystemExit()
# fake time.time
ts = self.fake_time
self.fake_time += 1.0/self.framerate
if self.last_ts is None:
delta_t = 0
else:
delta_t = ts - self.last_ts
self.times.insert(0, delta_t)
if len(self.times) > self.window_size:
self.cumulative_time -= self.times.pop()
self.cumulative_time += delta_t
self.last_ts = ts
# Call functions scheduled for every frame
# Dupe list just in case one of the items unchedules itself
for item in list(self._schedule_items):
item.func(delta_t, *item.args, **item.kwargs)
# Call all scheduled interval functions and reschedule for future.
need_resort = False
# Dupe list just in case one of the items unchedules itself
for item in list(self._schedule_interval_items):
if item.next_ts > ts:
break
item.func(ts - item.last_ts, *item.args, **item.kwargs)
if item.interval:
# Try to keep timing regular, even if overslept this time;
# but don't schedule in the past (which could lead to
# infinitely-worsing error).
item.next_ts = item.last_ts + item.interval
item.last_ts = ts
if item.next_ts <= ts:
if ts - item.next_ts < 0.05:
# Only missed by a little bit, keep the same schedule
item.next_ts = ts + item.interval
else:
# Missed by heaps, do a soft reschedule to avoid
# lumping everything together.
item.next_ts = self._get_soft_next_ts(ts, item.interval)
# Fake last_ts to avoid repeatedly over-scheduling in
# future. Unfortunately means the next reported dt is
# incorrect (looks like interval but actually isn't).
item.last_ts = item.next_ts - item.interval
need_resort = True
# Remove finished one-shots.
self._schedule_interval_items = \
[item for item in self._schedule_interval_items \
if item.next_ts > ts]
if need_resort:
# TODO bubble up changed items might be faster
self._schedule_interval_items.sort(key=lambda a: a.next_ts)
return delta_t
class Director(event.EventDispatcher):
"""Class that creates and handle the main Window and manages how
and when to execute the Scenes
You should not directly instantiate the class, instead you do::
from cocos.director import director
to access the only one Director instance.
"""
#: a dict with locals for the interactive python interpreter (fill with what you need)
interpreter_locals = {}
def init(self, *args, **kwargs):
"""Initializes the Director creating the main window.
Keyword arguments are passed to pyglet.window.Window().
All the valid arguments can be found here:
- http://www.pyglet.org/doc/1.1/api/pyglet.window.Window-class.html
:rtype: pyglet.window.Window
:returns: The main window, an instance of pyglet.window.Window class.
"""
#: whether or not the FPS are displayed
self.show_FPS = False
#: stack of scenes
self.scene_stack = []
#: scene that is being run
self.scene = None
#: this is the next scene that will be shown
self.next_scene = None
# python interpreter
self.python_interpreter = None
#: whether or not to show the python interpreter
self.show_interpreter = False
# pop out the Cocos-specific flags
self.do_not_scale_window = kwargs.pop('do_not_scale', False)
audio_backend = kwargs.pop('audio_backend', 'pyglet')
audio_settings = kwargs.pop('audio', {})
# handle pyglet 1.1.x vs 1.2dev differences in fullscreen
self._window_virtual_width = kwargs.get('width', None)
self._window_virtual_height = kwargs.get('height', None)
if pyglet.version.startswith('1.1') and kwargs.get('fullscreen', False):
# pyglet 1.1.x dont allow fullscreen with explicit width or height
kwargs.pop('width', 0)
kwargs.pop('height', 0)
#: pyglet's window object
self.window = window.Window( *args, **kwargs )
# complete the viewport geometry info, both virtual and real,
# also set the appropiate on_resize handler
if self._window_virtual_width is None:
self._window_virtual_width = self.window.width
if self._window_virtual_height is None:
self._window_virtual_height = self.window.height
self._window_virtual_aspect = (
self._window_virtual_width / float( self._window_virtual_height ))
self._offset_x = 0
self._offset_y = 0
if self.do_not_scale_window:
resize_handler = self.unscaled_resize_window
else:
resize_handler = self.scaled_resize_window
# the offsets and size for the viewport will be proper after this
self._resize_no_events = True
resize_handler(self.window.width, self.window.height)
self._resize_no_events = False
self.window.push_handlers(on_resize=resize_handler)
self.window.push_handlers(self.on_draw)
# opengl settings
self.set_alpha_blending()
# default handler
self.window.push_handlers( DefaultHandler() )
# Environment variable COCOS2d_NOSOUND=1 overrides audio settings
if getenv('COCOS2D_NOSOUND', None) == '1' or audio_backend == 'pyglet':
audio_settings = None
# if audio is not working, better to not work at all. Except if
# explicitely instructed to continue
if not cocos.audio._working and audio_settings is not None:
from cocos.audio.exceptions import NoAudioError
msg = "cocos.audio isn't able to work without needed dependencies. " \
"Try installing pygame for fixing it, or forcing no audio " \
"mode by calling director.init with audio=None, or setting the " \
"COCOS2D_NOSOUND=1 variable in your env."
raise NoAudioError(msg)
# Audio setup:
#TODO: reshape audio to not screw unittests
import os
if not os.environ.get('cocos_utest', False):
cocos.audio.initialize(audio_settings)
return self.window
fps_display = None
def set_show_FPS(self, value):
if value and self.fps_display is None:
self.fps_display = clock.ClockDisplay()
elif not value and self.fps_display is not None:
self.fps_display.unschedule()
self.fps_display.label.delete()
self.fps_display = None
show_FPS = property(lambda self: self.fps_display is not None,
set_show_FPS)
def run(self, scene):
"""Runs a scene, entering in the Director's main loop.
:Parameters:
`scene` : `Scene`
The scene that will be run.
"""
self.scene_stack.append( self.scene )
self._set_scene( scene )
event_loop.run()
def set_recorder(self, framerate, template="frame-%d.png", duration=None):
'''Will replace the system clock so that now we can ensure a steady
frame rate and save one image per frame
:Parameters
`framerate`: int
the number of frames per second
`template`: str
the template that will be completed with an in for the name of the files
`duration`: float
the amount of seconds to record, or 0 for infinite
'''
pyglet.clock._default = ScreenReaderClock(framerate, template, duration)
def on_draw( self ):
"""Callback to draw the window.
It propagates the event to the running scene."""
if self.window.width==0 or self.window.height==0: #
return
self.window.clear()
if self.next_scene is not None:
self._set_scene( self.next_scene )
if not self.scene_stack:
pyglet.app.exit()
# draw all the objects
self.scene.visit()
# finally show the FPS
if self.show_FPS:
self.fps_display.draw()
if self.show_interpreter:
self.python_interpreter.visit()
def push(self, scene):
"""Suspends the execution of the running scene, pushing it
on the stack of suspended scenes. The new scene will be executed.
:Parameters:
`scene` : `Scene`
It is the scene that will be run.
"""
self.dispatch_event("on_push", scene )
def on_push( self, scene ):
self.next_scene = scene
self.scene_stack.append( self.scene )
def pop(self):
"""Pops out a scene from the queue. This scene will replace the running one.
The running scene will be deleted. If there are no more scenes in the stack
the execution is terminated.
"""
self.dispatch_event("on_pop")
def on_pop(self):
self.next_scene = self.scene_stack.pop()
def replace(self, scene):
"""Replaces the running scene with a new one. The running scene is terminated.
:Parameters:
`scene` : `Scene`
It is the scene that will be run.
"""
self.next_scene = scene
def _set_scene(self, scene ):
"""Change to a new scene.
"""
self.next_scene = None
if self.scene is not None:
self.scene.on_exit()
self.scene.enable_handlers( False )
old = self.scene
self.scene = scene
self.scene.enable_handlers( True )
scene.on_enter()
return old
#
# Window Helper Functions
#
def get_window_size( self ):
"""Returns the size of the window when it was created, and not the
actual size of the window.
Usually you don't want to know the current window size, because the
Director() hides the complexity of rescaling your objects when
the Window is resized or if the window is made fullscreen.
If you created a window of 640x480, the you should continue to place
your objects in a 640x480 world, no matter if your window is resized or not.
Director will do the magic for you.
:rtype: (x,y)
:returns: The size of the window when it was created
"""
return ( self._window_virtual_width, self._window_virtual_height)
def get_virtual_coordinates( self, x, y ):
"""Transforms coordinates that belongs the *real* window size, to the
coordinates that belongs to the *virtual* window.
For example, if you created a window of 640x480, and it was resized
to 640x1000, then if you move your mouse over that window,
it will return the coordinates that belongs to the newly resized window.
Probably you are not interested in those coordinates, but in the coordinates
that belongs to your *virtual* window.
:rtype: (x,y)
:returns: Transformed coordinates from the *real* window to the *virtual* window
"""
x_diff = self._window_virtual_width / float( self.window.width - self._offset_x * 2 )
y_diff = self._window_virtual_height / float( self.window.height - self._offset_y * 2 )
adjust_x = (self.window.width * x_diff - self._window_virtual_width ) / 2
adjust_y = (self.window.height * y_diff - self._window_virtual_height ) / 2
return ( int( x_diff * x) - adjust_x, int( y_diff * y ) - adjust_y )
def scaled_resize_window( self, width, height):
"""One of two possible methods that are called when the main window is resized.
This implementation scales the display such that the initial resolution
requested by the programmer (the "logical" resolution) is always retained
and the content scaled to fit the physical display.
This implementation also sets up a 3D projection for compatibility with the
largest set of Cocos transforms.
The other implementation is `unscaled_resize_window`.
:Parameters:
`width` : Integer
New width
`height` : Integer
New height
"""
# physical view size
pw, ph = width, height
# virtual (desired) view size
vw, vh = self.get_window_size()
# desired aspect ratio
v_ar = vw/float(vh)
# usable width, heigh
uw = int(min(pw, ph*v_ar))
uh = int(min(ph, pw/v_ar))
ox = (pw-uw)//2
oy = (ph-uh)//2
self._offset_x = ox
self._offset_y = oy
self._usable_width = uw
self._usable_height = uh
self.set_projection()
if self._resize_no_events:
# setting viewport geometry, not handling an event
return
# deprecated - see issue 154
self.dispatch_event("on_resize", width, height)
self.dispatch_event("on_cocos_resize", self._usable_width, self._usable_height)
# dismiss the pyglet BaseWindow default 'on_resize' handler
return pyglet.event.EVENT_HANDLED
def unscaled_resize_window(self, width, height):
"""One of two possible methods that are called when the main window is resized.
This implementation does not scale the display but rather forces the logical
resolution to match the physical one.
This implementation sets up a 2D projection, resulting in the best pixel
alignment possible. This is good for text and other detailed 2d graphics
rendering.
The other implementation is `scaled_resize_window`.
:Parameters:
`width` : Integer
New width
`height` : Integer
New height
"""
self._usable_width = width
self._usable_height = height
if self._resize_no_events:
# setting viewport geometry, not handling an event
return
# deprecated - see issue 154
self.dispatch_event("on_resize", width, height)
self.dispatch_event("on_cocos_resize", self._usable_width, self._usable_height)
def set_projection(self):
'''Sets a 3D projection mantaining the aspect ratio of the original window size'''
# virtual (desired) view size
vw, vh = self.get_window_size()
glViewport(self._offset_x, self._offset_y, self._usable_width, self._usable_height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60, self._usable_width/float(self._usable_height), 0.1, 3000.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
gluLookAt( vw/2.0, vh/2.0, vh/1.1566, # eye
vw/2.0, vh/2.0, 0, # center
0.0, 1.0, 0.0 # up vector
)
#
# Misc functions
#
def set_alpha_blending( self, on=True ):
"""
Enables/Disables alpha blending in OpenGL
using the GL_ONE_MINUS_SRC_ALPHA algorithm.
On by default.
"""
if on:
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
else:
glDisable(GL_BLEND)
def set_depth_test( sefl, on=True ):
'''Enables z test. On by default
'''
if on:
glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
else:
glDisable( GL_DEPTH_TEST )
event_loop = pyglet.app.event_loop
if not hasattr(event_loop, "event"):
event_loop = pyglet.app.EventLoop()
director = Director()
director.event = event_loop.event
"""The singleton; check `cocos.director.Director` for details on usage.
Don't instantiate Director(). Just use this singleton."""
director.interpreter_locals["director"] = director
director.interpreter_locals["cocos"] = cocos
Director.register_event_type('on_push')
Director.register_event_type('on_pop')
Director.register_event_type('on_resize')
Director.register_event_type('on_cocos_resize')
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
__docformat__ = 'restructuredtext'
class Rect(object):
'''Define a rectangular area.
Many convenience handles and other properties are also defined - all of
which may be assigned to which will result in altering the position
and sometimes dimensions of the Rect:
- top -- y pixel extent
- bottom -- y pixel extent
- left -- x pixel extent
- right -- x pixel extent
- position -- (x, y) of bottom-left corner pixel
- origin -- (x, y) of bottom-left corner pixel
- center -- (x, y) of center pixel
- topleft -- (x, y) of top-left corner pixel
- topright -- (x, y) of top-right corner pixel
- bottomleft -- (x, y) of bottom-left corner pixel
- bottomright -- (x, y) of bottom-right corner pixel
- midtop -- (x, y) of middle of top side pixel
- midbottom -- (x, y) of middle of bottom side pixel
- midleft -- (x, y) of middle of left side pixel
- midright -- (x, y) of middle of right side pixel
- size -- (width, height) of rect
The Rect area includes the bottom and left borders but not the top and
right borders.
'''
def __init__(self, x, y, width, height):
'''Create a Rect with the bottom-left corner at (x, y) and
dimensions (width, height).
'''
self._x, self._y = x, y
self._width, self._height = width, height
def __nonzero__(self):
return bool(self.width and self.height)
def __repr__(self):
return 'Rect(xy=%.4g,%.4g; wh=%.4g,%.4g)'%(self.x, self.y,
self.width, self.height)
def __eq__(self, other):
'''Compare the two rects.
>>> r1 = Rect(0, 0, 10, 10)
>>> r1 == Rect(0, 0, 10, 10)
True
>>> r1 == Rect(1, 0, 10, 10)
False
>>> r1 == Rect(0, 1, 10, 10)
False
>>> r1 == Rect(0, 0, 11, 10)
False
>>> r1 == Rect(0, 0, 10, 11)
False
'''
return (self.x == other.x and self.y == other.y and
self.width == other.width and self.height == other.height)
def __ne__(self, other):
'''Compare the two rects.
>>> r1 = Rect(0, 0, 10, 10)
>>> r1 != Rect(0, 0, 10, 10)
False
>>> r1 != Rect(1, 0, 10, 10)
True
>>> r1 != Rect(0, 1, 10, 10)
True
>>> r1 != Rect(0, 0, 11, 10)
True
>>> r1 != Rect(0, 0, 10, 11)
True
'''
return not (self == other)
def copy(self):
return self.__class__(self.x, self.y, self.width, self.height)
# the following four properties will most likely be overridden in a
# subclass
def set_x(self, value): self._x = value
x = property(lambda self: self._x, set_x)
def set_y(self, value): self._y = value
y = property(lambda self: self._y, set_y)
def set_width(self, value): self._width = value
width = property(lambda self: self._width, set_width)
def set_height(self, value): self._height = value
height = property(lambda self: self._height, set_height)
def contains(self, x, y):
'''Return boolean whether the point defined by x, y is inside the
rect area.
'''
if x < self.x or x > self.x + self.width: return False
if y < self.y or y > self.y + self.height: return False
return True
def intersects(self, other):
'''Return boolean whether the "other" rect (an object with .x, .y,
.width and .height attributes) overlaps this Rect in any way.
'''
if self.x + self.width < other.x: return False
if other.x + other.width < self.x: return False
if self.y + self.height < other.y: return False
if other.y + other.height < self.y: return False
return True
def clippedBy(self, other):
'''Determine whether this rect is clipped by the other rect.
>>> r1 = Rect(0, 0, 10, 10)
>>> r2 = Rect(1, 1, 9, 9)
>>> r2.clippedBy(r1) # r2 fits inside r1
False
>>> r1.clippedBy(r2) # r1 is clipped by r2
True
>>> r2 = Rect(1, 1, 11, 11)
>>> r1.intersect(r2)
Rect(xy=1,1; wh=9,9)
>>> r1.clippedBy(r2)
True
>>> r2.intersect(r1)
Rect(xy=1,1; wh=9,9)
>>> r2.clippedBy(r1)
True
>>> r2 = Rect(11, 11, 1, 1)
>>> r1.clippedBy(r2)
True
'''
if self.intersects(other): return True
if i.x > self.x: return True
if i.y > self.y: return True
if i.width < self.width: return True
if i.height < self.height: return True
return False
def intersect(self, other):
'''Find the intersection of two Rects.
>>> r1 = Rect(0, 51, 200, 17)
>>> r2 = Rect(0, 64, 200, 55)
>>> r1.intersect(r2)
Rect(xy=0,64; wh=200,4)
>>> r1 = Rect(0, 64, 200, 55)
>>> r2 = Rect(0, 0, 200, 17)
>>> print r1.intersect(r2)
None
>>> r1 = Rect(10, 10, 10, 10)
>>> r2 = Rect(20, 20, 10, 10)
>>> print r1.intersect(r2)
None
>>> bool(Rect(0, 0, 1, 1))
True
>>> bool(Rect(0, 0, 1, 0))
False
>>> bool(Rect(0, 0, 0, 1))
False
>>> bool(Rect(0, 0, 0, 0))
False
'''
s_tr_x, s_tr_y = self.topright
o_tr_x, o_tr_y = other.topright
bl_x = max(self.x, other.x)
bl_y = max(self.y, other.y)
tr_x = min(s_tr_x, o_tr_x)
tr_y = min(s_tr_y, o_tr_y)
w, h = max(0, tr_x-bl_x), max(0, tr_y-bl_y)
if not w or not h:
return None
return self.__class__(bl_x, bl_y, w, h)
def set_position(self, value): self._x, self._y = value
position = property(lambda self: (self._x, self._y), set_position)
def set_size(self, value): self._width, self._height = value
size = property(lambda self: (self._width, self._height), set_size)
def get_origin(self): return self.x, self.y
def set_origin(self, origin): self.x, self.y = origin
origin = property(get_origin, set_origin)
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)
def get_left(self): return self.x
def set_left(self, x): self.x = x
left = property(get_left, set_left)
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)
def get_center(self):
return (self.x + self.width/2, self.y + self.height/2)
def set_center(self, center):
x, y = center
self.position = (x - self.width/2, y - self.height/2)
center = property(get_center, set_center)
def get_midtop(self):
return (self.x + self.width/2, self.y + self.height)
def set_midtop(self, midtop):
x, y = midtop
self.position = (x - self.width/2, y - self.height)
midtop = property(get_midtop, set_midtop)
def get_midbottom(self):
return (self.x + self.width/2, self.y)
def set_midbottom(self, midbottom):
x, y = midbottom
self.position = (x - self.width/2, y)
midbottom = property(get_midbottom, set_midbottom)
def get_midleft(self):
return (self.x, self.y + self.height/2)
def set_midleft(self, midleft):
x, y = midleft
self.position = (x, y - self.height/2)
midleft = property(get_midleft, set_midleft)
def get_midright(self):
return (self.x + self.width, self.y + self.height/2)
def set_midright(self, midright):
x, y = midright
self.position = (x - self.width, y - self.height/2)
midright = property(get_midright, set_midright)
def get_topleft(self):
return (self.x, self.y + self.height)
def set_topleft(self, position):
x, y = position
self.position = (x, y - self.height)
topleft = property(get_topleft, set_topleft)
def get_topright(self):
return (self.x + self.width, self.y + self.height)
def set_topright(self, position):
x, y = position
self.position = (x - self.width, y - self.height)
topright = property(get_topright, set_topright)
def get_bottomright(self):
return (self.x + self.width, self.y)
def set_bottomright(self, position):
x, y = position
self.position = (x - self.width, y)
bottomright = property(get_bottomright, set_bottomright)
def get_bottomleft(self):
return (self.x, self.y)
def set_bottomleft(self, position):
self.x, self.y = position
bottomleft = property(get_bottomleft, set_bottomleft)
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
#
# Ideas borrowed from:
# pygext: http://opioid-interactive.com/~shang/projects/pygext/
# pyglet astraea: http://www.pyglet.org
# Grossini's Hell: http://www.pyweek.org/e/Pywiii/
#
"""A `Layer` that implements a simple menu
Menu
====
This module provides a Menu class. Menus can contain regular items
(which trigger a function when selected), toggle items (which toggle a flag when selected),
or entry items (which lets you enter alphanumeric data).
To use a menu in your code, just subclass `Menu` and add the menu to an `Scene` or
another `Layer`.
"""
__docformat__ = 'restructuredtext'
import pyglet
from pyglet import font
from pyglet.window import key
from pyglet.gl import *
import pyglet.graphics
from layer import *
from director import *
from cocosnode import *
from actions import *
from sprite import Sprite
import rect
__all__ = [ 'Menu', # menu class
'MenuItem', 'ToggleMenuItem', # menu items classes
'MultipleMenuItem', 'EntryMenuItem', 'ImageMenuItem',
'ColorMenuItem',
'verticalMenuLayout', 'fixedPositionMenuLayout', # Different menu layou functions
'CENTER', 'LEFT', 'RIGHT', 'TOP', 'BOTTOM', # menu aligment
'shake', 'shake_back','zoom_in','zoom_out' # Some useful actions for the menu items
]
#
# Class Menu
#
# Horizontal Align
CENTER = font.Text.CENTER
LEFT = font.Text.LEFT
RIGHT = font.Text.RIGHT
# Vertical Align
TOP = font.Text.TOP
BOTTOM = font.Text.BOTTOM
def verticalMenuLayout (menu):
width, height = director.get_window_size()
fo = font.load(menu.font_item['font_name'], menu.font_item['font_size'])
fo_height = int( (fo.ascent - fo.descent) * 0.9 )
if menu.menu_halign == CENTER:
pos_x = width // 2
elif menu.menu_halign == RIGHT:
pos_x = width - menu.menu_hmargin
elif menu.menu_halign == LEFT:
pos_x = menu.menu_hmargin
else:
raise Exception("Invalid anchor_x value for menu")
for idx,i in enumerate( menu.children):
item = i[1]
if menu.menu_valign == CENTER:
pos_y = (height + (len(menu.children) - 2 * idx)
* fo_height - menu.title_height) * 0.5
elif menu.menu_valign == TOP:
pos_y = (height - ((idx + 0.8) * fo_height )
- menu.title_height - menu.menu_vmargin)
elif menu.menu_valign == BOTTOM:
pos_y = (0 + fo_height * (len(menu.children) - idx) +
menu.menu_vmargin)
item.transform_anchor = (pos_x, pos_y)
item.generateWidgets (pos_x, pos_y, menu.font_item,
menu.font_item_selected)
def fixedPositionMenuLayout (positions):
def fixedMenuLayout(menu):
width, height = director.get_window_size()
for idx,i in enumerate( menu.children):
item = i[1]
pos_x = positions[idx][0]
pos_y = positions[idx][1]
item.transform_anchor = (pos_x, pos_y)
item.generateWidgets (pos_x, pos_y, menu.font_item,
menu.font_item_selected)
return fixedMenuLayout
class Menu(Layer):
"""Abstract base class for menu layers.
Normal usage is:
- create a subclass
- override __init__ to set all style attributes,
and then call `create_menu()`
- Finally you shall add the menu to an `Scene` or another `Layer`
"""
is_event_handler = True #: Receives pyglet events
select_sound = None
activate_sound = None
def __init__( self, title = ''):
super(Menu, self).__init__()
#
# Items and Title
#
self.title = title
self.title_text = None
self.menu_halign = CENTER
self.menu_valign = CENTER
self.menu_hmargin = 2 # Variable margins for left and right alignment
self.menu_vmargin = 2 # Variable margins for top and bottom alignment
#
# Menu default options
# Menus can be customized changing these variables
#
# Title
self.font_title = {
'text':'title',
'font_name':'Arial',
'font_size':56,
'color':(192,192,192,255),
'bold':False,
'italic':False,
'anchor_y':'center',
'anchor_x':'center',
'dpi':96,
'x':0, 'y':0,
}
self.font_item= {
'font_name':'Arial',
'font_size':32,
'bold':False,
'italic':False,
'anchor_y':'center',
'anchor_x':'center',
'color':(192,192,192,255),
'dpi':96,
}
self.font_item_selected = {
'font_name':'Arial',
'font_size':42,
'bold':False,
'italic':False,
'anchor_y':'center',
'anchor_x':'center',
'color':(255,255,255,255),
'dpi':96,
}
self.title_height = 0
self.schedule(lambda dt: None)
def _generate_title( self ):
width, height = director.get_window_size()
self.font_title['x'] = width // 2
self.font_title['text'] = self.title
self.title_label = pyglet.text.Label( **self.font_title )
self.title_label.y = height - self.title_label.content_height //2
fo = font.load( self.font_title['font_name'], self.font_title['font_size'] )
self.title_height = self.title_label.content_height
def _build_items(self, layout_strategy):
self.font_item_selected['anchor_x'] = self.menu_halign
self.font_item_selected['anchor_y'] = 'center'
self.font_item['anchor_x'] = self.menu_halign
self.font_item['anchor_y'] = 'center'
layout_strategy(self)
self.selected_index = 0
self.children[ self.selected_index ][1].is_selected = True
def _select_item(self, new_idx):
if new_idx == self.selected_index:
return
if self.select_sound:
self.select_sound.play()
self.children[ self.selected_index][1].is_selected = False
self.children[ self.selected_index][1].on_unselected()
self.children[ new_idx ][1].is_selected = True
self.children[ new_idx ][1].on_selected()
self.selected_index = new_idx
def _activate_item( self ):
if self.activate_sound:
self.activate_sound.play()
self.children[ self.selected_index][1].on_activated()
self.children[ self.selected_index ][1].on_key_press( key.ENTER, 0 )
def create_menu(self, items, selected_effect=None, unselected_effect=None,
activated_effect=None, layout_strategy=verticalMenuLayout):
"""Creates the menu
The order of the list important since the
first one will be shown first.
Example::
l = []
l.append( MenuItem('Options', self.on_new_game ) )
l.append( MenuItem('Quit', self.on_quit ) )
self.create_menu( l, zoom_in(), zoom_out() )
:Parameters:
`items` : list
list of `BaseMenuItem` that will be part of the `Menu`
`selected_effect` : function
This action will be executed when the `BaseMenuItem` is selected
`unselected_effect` : function
This action will be executed when the `BaseMenuItem` is unselected
`activated_effect` : function
this action will executed when the `BaseMenuItem` is activated (pressing Enter or by clicking on it)
"""
z=0
for i in items:
# calling super.add(). Z is important to mantain order
self.add( i, z=z )
i.activated_effect = activated_effect
i.selected_effect = selected_effect
i.unselected_effect = unselected_effect
i.item_halign = self.menu_halign
i.item_valign = self.menu_valign
z += 1
self._generate_title() # If you generate the title after the items
# the V position of the items can't consider the title's height
if items:
self._build_items(layout_strategy)
def draw( self ):
glPushMatrix()
self.transform()
self.title_label.draw()
glPopMatrix()
def on_text( self, text ):
if text=='\r':
return
return self.children[self.selected_index][1].on_text(text)
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE:
self.on_quit()
return True
elif symbol in (key.ENTER, key.NUM_ENTER):
self._activate_item()
return True
elif symbol in (key.DOWN, key.UP):
if symbol == key.DOWN:
new_idx = self.selected_index + 1
elif symbol == key.UP:
new_idx = self.selected_index - 1
if new_idx < 0:
new_idx = len(self.children) -1
elif new_idx > len(self.children) -1:
new_idx = 0
self._select_item( new_idx )
return True
else:
# send the menu item the rest of the keys
ret = self.children[self.selected_index][1].on_key_press(symbol, modifiers)
# play sound if key was handled
if ret and self.activate_sound:
self.activate_sound.play()
return ret
def on_mouse_release( self, x, y, buttons, modifiers ):
(x,y) = director.get_virtual_coordinates(x,y)
if self.children[ self.selected_index ][1].is_inside_box(x,y):
self._activate_item()
def on_mouse_motion( self, x, y, dx, dy ):
(x,y) = director.get_virtual_coordinates(x,y)
for idx,i in enumerate( self.children):
item = i[1]
if item.is_inside_box( x, y):
self._select_item( idx )
break
class BaseMenuItem( CocosNode ):
"""An abstract menu item. It triggers a function when it is activated"""
selected_effect = None
unselected_effect = None
activated_effect = None
def __init__(self, callback_func, *args, **kwargs):
"""Creates a new menu item
:Parameters:
`callback_func` : function
The callback function
"""
super( BaseMenuItem, self).__init__()
self.callback_func = callback_func
self.callback_args = args
self.callback_kwargs = kwargs
self.is_selected = False
self.item_halign = None
self.item_valign = None
self.item = None
self.item_selected = None
def get_item_width (self):
""" Returns the width of the item.
This method should be implemented by descendents.
:rtype: int
"""
return self.item.width
def get_item_height (self):
""" Returns the width of the item.
This method should be implemented by descendents.
:rtype: int
"""
return self.item.height
def generateWidgets (self, pos_x, pos_y, font_item, font_item_selected):
""" Generate a normal and a selected widget.
This method should be implemented by descendents.
"""
raise NotImplementedError
def get_item_x (self):
""" Return the x position of the item.
This method should be implemented by descendents.
:rtype: int
"""
return self.item.x
def get_item_y (self):
""" Return the y position of the item.
This method should be implemented by descendents.
:rtype: int
"""
return self.item.y
def get_box( self ):
"""Returns the box that contains the menu item.
:rtype: (x1,x2,y1,y2)
"""
width = self.get_item_width ()
height = self.get_item_height ()
if self.item_halign == CENTER:
x_diff = - width / 2
elif self.item_halign == RIGHT:
x_diff = - width
elif self.item_halign == LEFT:
x_diff = 0
else:
raise Exception("Invalid halign: %s" % str(self.item_halign) )
y_diff = - height/ 2
x1 = self.get_item_x() + x_diff
y1 = self.get_item_y() + y_diff
# x1 += self.parent.x
# y1 += self.parent.y
# x2 = x1 + width
# y2 = y1 + height
# return (x1,y1,x2,y2)
return rect.Rect(x1,y1,width,height)
def draw( self ):
raise NotImplementedError
def on_key_press(self, symbol, modifiers):
if symbol == key.ENTER and self.callback_func:
self.callback_func(*self.callback_args, **self.callback_kwargs)
return True
def on_text( self, text ):
return True
def is_inside_box( self, x, y ):
"""Returns whether the point (x,y) is inside the menu item.
:rtype: bool
"""
# (ax,ay,bx,by) = self.get_box()
# if( x >= ax and x <= bx and y >= ay and y <= by ):
# return True
# return False
rect = self.get_box()
p = self.point_to_local( (x,y) )
return rect.contains( p.x, p.y )
def on_selected( self ):
if self.selected_effect:
self.stop()
self.do( self.selected_effect )
def on_unselected( self ):
if self.unselected_effect:
self.stop()
self.do( self.unselected_effect )
def on_activated( self ):
if self.activated_effect:
self.stop()
self.do( self.activated_effect )
class MenuItem (BaseMenuItem):
"""A menu item that shows a label. """
def __init__ (self, label, callback_func, *args, **kwargs):
"""Creates a new menu item
:Parameters:
`label` : string
The label the of the menu item
`callback_func` : function
The callback function
"""
self.label = label
super (MenuItem, self).__init__(callback_func, *args, **kwargs)
def get_item_width (self):
return self.item.content_width
def get_item_height (self):
return self.item.content_height
def generateWidgets (self, pos_x, pos_y, font_item, font_item_selected):
font_item['x'] = int(pos_x)
font_item['y'] = int(pos_y)
font_item['text'] = self.label
self.item = pyglet.text.Label(**font_item )
font_item_selected['x'] = int(pos_x)
font_item_selected['y'] = int(pos_y)
font_item_selected['text'] = self.label
self.item_selected = pyglet.text.Label( **font_item_selected )
def draw( self ):
glPushMatrix()
self.transform()
if self.is_selected:
self.item_selected.draw()
else:
self.item.draw()
glPopMatrix()
class ImageMenuItem (BaseMenuItem):
""" A menu item that shows a selectable Image """
def __init__ (self, name, callback_func, *args, **kwargs):
self.image = pyglet.resource.image (name)
super (ImageMenuItem, self).__init__(callback_func, *args, **kwargs)
def generateWidgets (self, pos_x, pos_y, font_item, font_item_selected):
anchors = {'left': 0, 'center': 0.5, 'right': 1, 'top': 1, 'bottom': 0}
anchor=(anchors[font_item['anchor_x']] * self.image.width,
anchors[font_item['anchor_y']] * self.image.height)
self.item = Sprite(self.image, anchor=anchor, opacity=255,
color=font_item['color'][:3])
self.item.scale = font_item['font_size'] / float(self.item.height )
self.item.position = int(pos_x), int(pos_y)
self.selected_item = Sprite(self.image, anchor=anchor,
color=font_item_selected['color'][:3])
self.selected_item.scale = (font_item_selected['font_size'] /
float(self.selected_item.height))
self.selected_item.position = int(pos_x), int(pos_y)
def draw (self):
glPushMatrix()
self.transform()
if self.is_selected:
self.selected_item.draw()
else:
self.item.draw()
glPopMatrix()
class MultipleMenuItem( MenuItem ):
"""A menu item for switching between multiple values.
Example::
self.volumes = ['Mute','10','20','30','40','50','60','70','80','90','100']
items.append( MultipleMenuItem(
'SFX volume: ',
self.on_sfx_volume,
self.volumes,
8 ) )
"""
def __init__(self, label, callback_func, items, default_item=0):
"""Creates a Multiple Menu Item
:Parameters:
`label` : string
Item's label
`callback_func` : function
Callback function
`items` : list
List of strings containing the values
`default_item` : integer
Default item of the list. It is an index of the list. Default: 0
"""
self.my_label = label
self.items = items
self.idx = default_item
if self.idx < 0 or self.idx >= len(self.items):
raise Exception("Index out of bounds")
super( MultipleMenuItem, self).__init__( self._get_label(), callback_func )
def _get_label(self):
return self.my_label+self.items[self.idx]
def on_key_press(self, symbol, modifiers):
if symbol == key.LEFT:
self.idx = max(0, self.idx-1)
elif symbol in (key.RIGHT, key.ENTER):
self.idx = min(len(self.items)-1, self.idx+1)
if symbol in (key.LEFT, key.RIGHT, key.ENTER):
self.item.text = self._get_label()
self.item_selected.text = self._get_label()
self.callback_func( self.idx )
return True
class ToggleMenuItem( MultipleMenuItem ):
'''A menu item for a boolean toggle option.
Example::
items.append( ToggleMenuItem('Show FPS:', self.on_show_fps, director.show_FPS) )
'''
def __init__(self, label, callback_func, value=False ):
"""Creates a Toggle Menu Item
:Parameters:
`label` : string
Item's label
`callback_func` : function
Callback function
`value` : bool
Default value of the item: False is 'OFF', True is 'ON'. Default:False
"""
super(ToggleMenuItem, self).__init__( label, callback_func, ['OFF','ON'], int(value) )
def on_key_press( self, symbol, mod ):
if symbol in (key.LEFT, key.RIGHT, key.ENTER):
self.idx += 1
if self.idx > 1:
self.idx = 0
self.item.text = self._get_label()
self.item_selected.text = self._get_label()
self.callback_func( int(self.idx) )
return True
class EntryMenuItem(MenuItem):
"""A menu item for entering a value.
When selected, ``self.value`` is toggled, the callback function is
called with ``self.value`` as argument."""
value = property(lambda self: u''.join(self._value),
lambda self, v: setattr(self, '_value', list(v)))
def __init__(self, label, callback_func, value, max_length=0 ):
"""Creates an Entry Menu Item
:Parameters:
`label` : string
Item's label
`callback_func` : function
Callback function taking one argument.
`value` : String
Default value: any string
`max_length` : integer
Maximum value length (Defaults to 0 for unbound length)
"""
self._value = list(value)
self._label = label
super(EntryMenuItem, self).__init__( "%s %s" %(label,value), callback_func )
self.max_length = max_length
def on_text( self, text ):
if self.max_length == 0 or len(self._value) < self.max_length:
self._value.append(text)
self._calculate_value()
return True
def on_key_press(self, symbol, modifiers):
if symbol == key.BACKSPACE:
try:
self._value.pop()
except IndexError:
pass
self._calculate_value()
return True
def _calculate_value( self ):
new_text = u"%s %s" % (self._label, self.value)
self.item.text = new_text
self.item_selected.text = new_text
self.callback_func(self.value)
class ColorMenuItem( MenuItem ):
"""A menu item for selecting a color.
Example::
colors = [(255, 255, 255), (100, 200, 100), (200, 50, 50)]
items.append( ColorMenuItem(
'Jacket:',
self.on_jacket_color,
colors ))
"""
def __init__(self, label, callback_func, items, default_item=0):
"""Creates a Color Menu Item
:Parameters:
`label` : string
Item's label
`callback_func` : function
Callback function
`items` : list
List of thre-element tuples describing the color choices
`default_item` : integer
Default item of the list. It is an index of the list. Default: 0
"""
self.my_label = label
self.items = items
self.idx = default_item
if self.idx < 0 or self.idx >= len(self.items):
raise Exception("Index out of bounds")
super( ColorMenuItem, self).__init__( self._get_label(), callback_func )
def _get_label(self):
return self.my_label + " "
def on_key_press(self, symbol, modifiers):
if symbol == key.LEFT:
self.idx = max(0, self.idx-1)
elif symbol in (key.RIGHT, key.ENTER):
self.idx = min(len(self.items)-1, self.idx+1)
if symbol in (key.LEFT, key.RIGHT, key.ENTER):
self.item.text = self._get_label()
self.item_selected.text = self._get_label()
self.callback_func( self.idx )
return True
def generateWidgets (self, pos_x, pos_y, font_item, font_item_selected):
font_item['x'] = int(pos_x)
font_item['y'] = int(pos_y)
font_item['text'] = self.my_label
self.item = pyglet.text.Label(**font_item )
self.item.labelWidth=self.item.content_width
self.item.text = self.label
font_item_selected['x'] = int(pos_x)
font_item_selected['y'] = int(pos_y)
font_item_selected['text'] = self.my_label
self.item_selected = pyglet.text.Label( **font_item_selected )
self.item_selected.labelWidth=self.item_selected.content_width
self.item_selected.text = self.label
def draw(self, *args, **kwargs):
super(ColorMenuItem, self).draw()
glPushMatrix()
self.transform()
if self.is_selected:
item = self.item_selected
else:
item = self.item
x1 = int(item._get_left() + item.labelWidth * 1.05)
y1 = int(item.y - item.content_height / 2)
y2 = int(item.y + item.content_height / 3)
x2 = int(x1 + (y2 - y1) * 2)
pyglet.graphics.draw(4, pyglet.graphics.GL_QUADS,
('v2f', (x1, y1, x1, y2, x2, y2, x2, y1)),
('c3B', self.items[self.idx] * 4))
glPopMatrix()
def shake():
'''Predefined action that performs a slight rotation and then goes back to the original rotation
position.
'''
angle = 05
duration = 0.05
rot = Accelerate(RotateBy( angle, duration ), 2)
rot2 = Accelerate(RotateBy( -angle*2, duration), 2)
return rot + (rot2 + Reverse(rot2)) * 2 + Reverse(rot)
def shake_back():
'''Predefined action that rotates to 0 degrees in 0.1 seconds'''
return RotateTo(0,0.1)
def zoom_in():
'''Predefined action that scales to 1.5 factor in 0.2 seconds'''
return ScaleTo( 1.5, duration=0.2 )
def zoom_out():
'''Predefined action that scales to 1.0 factor in 0.2 seconds'''
return ScaleTo( 1.0, duration=0.2 )
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Utility classes for rendering to a texture.
It is mostly used for internal implementation of cocos, you normally shouldn't
need it. If you are curious, check implementation of effects to see an example.
"""
__docformat__ = 'restructuredtext'
from gl_framebuffer_object import FramebufferObject
from pyglet.gl import *
from director import director
from pyglet import image
import pyglet
# Auxiliar classes for render-to-texture
_best_grabber = None
__all__ = ['TextureGrabber']
def TextureGrabber():
"""Returns an instance of the best texture grabbing class"""
# Why this isn't done on module import? Because we need an initialized
# GL Context to query availability of extensions
global _best_grabber
if _best_grabber is not None:
return _best_grabber()
# Preferred method: framebuffer object
try:
# TEST XXX
#_best_grabber = GenericGrabber
_best_grabber = FBOGrabber
return _best_grabber()
except:
import traceback
traceback.print_exc()
# Fallback: GL generic grabber
raise Exception("ERROR: GPU doesn't support Frame Buffers Objects. Can't continue")
# _best_grabber = GenericGrabber
# return _best_grabber()
class _TextureGrabber(object):
def __init__(self):
"""Create a texture grabber."""
def grab(self, texture):
"""Capture the current screen."""
def before_render(self, texture):
"""Setup call before rendering begins."""
def after_render(self, texture):
"""Rendering done, make sure texture holds what has been rendered."""
class GenericGrabber(_TextureGrabber):
"""A simple render-to-texture mechanism. Destroys the current GL display;
and considers the whole layer as opaque. But it works in any GL
implementation."""
def __init__(self):
self.before = None
x1 = y1 = 0
x2, y2 = director.get_window_size()
self.vertex_list = pyglet.graphics.vertex_list(4,
('v2f', [x1, y1, x2, y1, x2, y2, x1, y2]),
('c4B', [255,255,255,255]*4)
)
def before_render (self, texture):
#self.before = image.get_buffer_manager().get_color_buffer()
director.window.clear()
def after_render (self, texture):
buffer = image.get_buffer_manager().get_color_buffer()
texture.blit_into(buffer, 0, 0, 0)
director.window.clear()
return
self.before.blit(0,0)
glEnable(self.before.texture.target)
glBindTexture(self.before.texture.target, self.before.texture.id)
glPushAttrib(GL_COLOR_BUFFER_BIT)
self.vertex_list.draw(pyglet.gl.GL_QUADS)
glPopAttrib()
glDisable(self.before.texture.target)
class PbufferGrabber(_TextureGrabber):
"""A render-to texture mechanism using pbuffers.
Requires pbuffer extensions. Currently only implemented in GLX.
Not working yet, very untested
TODO: finish pbuffer grabber
"""
def grab (self, texture):
self.pbuf = Pbuffer(director.window, [
GLX_CONFIG_CAVEAT, GLX_NONE,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_DEPTH_SIZE, 24,
GLX_DOUBLEBUFFER, 1,
])
def before_render (self, texture):
self.pbuf.switch_to()
gl.glViewport(0, 0, self.pbuf.width, self.pbuf.height)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glLoadIdentity()
gl.glOrtho(0, self.pbuf.width, 0, self.pbuf.height, -1, 1)
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glEnable (gl.GL_TEXTURE_2D)
def after_render (self, texture):
buffer = image.get_buffer_manager().get_color_buffer()
texture.blit_into (buffer, 0, 0, 0)
director.window.switch_to()
class FBOGrabber(_TextureGrabber):
"""Render-to texture system based on framebuffer objects (the GL
extension). It is quite fast and portable, but requires a recent GL
implementation/driver.
Requires framebuffer_object extensions"""
def __init__ (self):
# This code is on init to make creation fail if FBOs are not available
self.fbuf = FramebufferObject()
self.fbuf.check_status()
def grab (self, texture):
self.fbuf.bind()
self.fbuf.texture2d (texture)
self.fbuf.check_status()
self.fbuf.unbind()
def before_render (self, texture):
self.fbuf.bind()
glClear(GL_COLOR_BUFFER_BIT)
def after_render (self, texture):
self.fbuf.unbind()
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
Tile Maps
=========
Tile maps are made of three components:
images
Images are from individual files for from image atlases in a single file.
tiles
Tiles may be stand-alone or part of a TileSet.
maps
MapLayers are made of either rectangular or hexagonal Cells which
reference the tiles used to draw the cell.
The intent is that you may have a tile set defined in one XML file
which is shared amongst many map files (or indeed within a single
XML file). Images may be shared amongst multiple tiles with the tiles
adding different meta-data in each case.
These may be constructed manually or loaded from XML resource files which
are used to store the specification of tile sets and tile maps. A given
resource XML file may define multiple tile sets and maps and may even
reference other external XML resource files. This would allow a single
tile set to be used by multiple tile maps.
Maps
----
The RectMapLayer class extends the regular Cocos layer to handle a
regular grid of tile images, or Cells. The map layer may be manipulated
like any other Cocos layer. It also provides methods for interrogating
the map contents to find cells (eg. under the mouse) or neighboring
cells (up, down, left, right.)
Maps may be defined in Python code, but it is a little easier to do so
in XML. To support map editing the maps support round-tripping to XML.
The XML File Specification
--------------------------
Assuming the following XML file called "example.xml"::
<?xml version="1.0"?>
<resource>
<requires file="ground-tiles.xml" namespace="ground" />
<rectmap id="level1">
<column>
<cell tile="ground:grass" />
<cell tile="ground:house">
<property type="bool" name="secretobjective" value="True" />
</cell>
</column>
</map>
</resource>
You may load that resource and examine it::
>>> r = load('example.xml')
>>> map = r['level1']
and then, assuming that level1 is a map::
>>> scene = cocos.scene.Scene(map)
and then either manually select the tiles to display:
>>> map.set_view(0, 0, window_width, window_height)
or if you wish for the level to scroll, you use the ScrollingManager::
>>> from cocos import layers
>>> manager = layers.ScrollingManager()
>>> manager.add(map)
and later set the focus with::
>>> manager.set_focus(focus_x, focus_y)
See the section on `controlling map scrolling`_ below for more detail.
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 <requires> tag::
<requires 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::
<requires file="road-tiles.xml" namespace="road" />
If a namespace is given then the element ids from the "road-tiles.xml"
will be prefixed by the namespace and a period, e.g. "road:bitumen".
Other tags within <resource> are::
<image file="" id="">
Loads file with pyglet.image.load and gives it the id which is used
by tiles to reference the image.
::
<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. Image atlas ids are optional as
they are currently not reference directly.
::
<tileset id="">
Sets up a TileSet object. Child tags are of the form::
<tile id="">
[<image ...>]
</tile>
The <image> tag is optional; these tiles may have only properties (or be
completely empty). The id is used by maps to reference the tile.
::
<rectmap id="" tile_size="" [origin=""]>
Sets up a RectMap object. Child tags are of the form::
<column>
<cell tile="" />
</column>
Map, Cell and Tile Properties
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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.
Properties are accessed on the map, cell or tile using common dict operations
with some extensions. Accessing a property on a **cell** will fall back to look
on the **tile** if it's not found on the cell.
If a cell has a property ``player-spawn`` (boolean) and the tile that the cell
uses has a property ``move-cost=1`` (int) then the following are true::
'player-spawn' in cell == True
cell.get('player-spawn') == True
cell['player-spawn'] == True
'player-spawn' in tile == False
tile.get('player-spawn') == None
tile['player-spawn'] --> raises KeyError
cell['move-cost'] == 1
You may additionally set properties on cells and tiles::
cell['player-postion'] = True
cell['burnt-out'] = True
and when the map is exported to XML these properties will also be exported.
Controlling Map Scrolling
-------------------------
You have three options for map scrolling:
1. never automatically scroll the map,
2. automatically scroll the map but stop at the map edges, and
3. scroll the map an allow the edge of the map to be displayed.
The first is possibly the easiest since you don't need to use a
ScrollingManager layer. You simple call map.set_view(x, y, w, h) on your
map layer giving the bottom-left corner coordinates and the dimensions
to display. This could be as simple as::
map.set_view(0, 0, map.px_width, map.px_height)
If you wish to have the map scroll around in response to player
movement the ScrollingManager from the cocos.scrolling module
may be used.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: resource.py 1078 2007-08-01 03:43:38Z r1chardj0n3s $'
import os
import math
import weakref
try:
from xml.etree import ElementTree
except ImportError:
import elementtree.ElementTree as ElementTree
import pyglet
from pyglet.gl import *
import cocos
from cocos.director import director
from cocos.rect import Rect
# Implement these classes for backwards compatibility; some older code
# expects ScrollableLayer and ScrollingManager to be in the tiles module.
from cocos import layer
class ScrollableLayer(layer.ScrollableLayer):
def __init__(self, parallax=1):
import warnings
warnings.warn('ScrollableLayer been has moved to cocos.layer',
DeprecationWarning, stacklevel=2)
super(ScrollableLayer, self).__init__(parallax=parallax)
class ScrollingManager(layer.ScrollingManager):
def __init__(self, viewport=None):
import warnings
warnings.warn('ScrollingManager been has moved to cocos.layer',
DeprecationWarning, stacklevel=2)
super(ScrollingManager, self).__init__(viewport=viewport)
class ResourceError(Exception):
pass
class TilesPropertyWithoutName(Exception):
pass
class TilesPropertyWithoutValue(Exception):
pass
class Resource(object):
'''Load some tile mapping resources from an XML file.
'''
cache = {}
def __init__(self, filename):
self.filename = filename
# id to map, tileset, etc.
self.contents = {}
# list of (namespace, Resource) from <requires> tags
self.requires = []
filename = self.find_file(filename)
tree = ElementTree.parse(filename)
root = tree.getroot()
if root.tag != 'resource':
raise ResourceError('document is <%s> instead of <resource>'%
root.name)
self.handle(root)
def find_file(self, filename):
if os.path.isabs(filename):
return filename
if os.path.exists(filename):
return filename
path = pyglet.resource.location(filename).path
return os.path.join(path, filename)
def resource_factory(self, tag):
for child in tag:
self.handle(child)
def requires_factory(self, tag):
resource = load(tag.get('file'))
self.requires.append((tag.get('namespace', ''), resource))
factories = {
'resource': resource_factory,
'requires': requires_factory,
}
@classmethod
def register_factory(cls, name):
def decorate(func):
cls.factories[name] = func
return func
return decorate
def handle(self, tag):
ref = tag.get('ref')
if not ref:
return self.factories[tag.tag](self, tag)
return self.get_resource(ref)
def __contains__(self, ref):
return ref in self.contents
def __getitem__(self, ref):
reqns = ''
id = ref
if ':' in ref:
reqns, id = ref.split(':', 1)
elif id in self.contents:
return self.contents[id]
for ns, res in self.requires:
if ns != reqns: continue
if id in res: return res[id]
raise KeyError(id)
def find(self, cls):
'''Find all elements of the given class in this resource.
'''
for k in self.contents:
if isinstance(self.contents[k], cls):
yield (k, self.contents[k])
def findall(self, cls, ns=''):
'''Find all elements of the given class in this resource and all
<requires>'ed resources.
'''
for k in self.contents:
if isinstance(self.contents[k], cls):
if ns:
yield (ns + ':' + k, self.contents[k])
else:
yield (k, self.contents[k])
for ns, res in self.requires:
for item in res.findall(cls, ns):
yield item
def add_resource(self, id, resource):
self.contents[id] = resource
def get_resource(self, ref):
return self[ref]
def save_xml(self, filename):
'''Save this resource's XML to the indicated file.
'''
# generate the XML
root = ElementTree.Element('resource')
root.tail = '\n'
for namespace, res in self.requires:
r = ElementTree.SubElement(root, 'requires', file=res.filename)
r.tail = '\n'
if namespace:
r.set('namespace', namespace)
for element in self.contents.values():
element._as_xml(root)
tree = ElementTree.ElementTree(root)
tree.write(filename)
_cache = weakref.WeakValueDictionary()
class _NOT_LOADED(object): pass
def load(filename):
'''Load resource(s) defined in the indicated XML file.
'''
# make sure we can find files relative to this one
dirname = os.path.dirname(filename)
if dirname and dirname not in pyglet.resource.path:
pyglet.resource.path.append(dirname)
pyglet.resource.reindex()
if filename in _cache:
if _cache[filename] is _NOT_LOADED:
raise ResourceError('Loop in XML files loading "%s"'%filename)
return _cache[filename]
_cache[filename] = _NOT_LOADED
obj = Resource(filename)
_cache[filename] = obj
return obj
#
# XML PROPERTY PARSING
#
_xml_to_python = dict(
unicode=unicode,
int=int,
float=float,
bool=lambda value: value != "False",
)
_python_to_xml = {
str: unicode,
unicode: unicode,
int: repr,
float: repr,
bool: repr,
}
_xml_type = {
str: 'unicode',
unicode: 'unicode',
int: 'int',
float: 'float',
bool: 'bool',
}
def _handle_properties(tag):
"""returns the properties dict reading from the etree node tag
:Parameters:
`tag` : xml.etree.ElementTree
node from which the properties are obtained
"""
properties = {}
for node in tag.findall('./property'):
name = node.get('name')
type = node.get('type') or 'unicode'
value = node.get('value')
if name is None:
raise TilesPropertyWithoutName("\nnode:\n%s"%ElementTree.tostring(node))
if value is None:
raise TilesPropertyWithoutValue("\nnode:\n%s"%ElementTree.tostring(node))
properties[name] = _xml_to_python[type](value)
return properties
#
# IMAGE and IMAGE ATLAS
#
@Resource.register_factory('image')
def image_factory(resource, tag):
filename = resource.find_file(tag.get('file'))
if not filename:
raise ResourceError('No file= on <image> tag')
image = pyglet.image.load(filename)
image.properties = _handle_properties(tag)
if tag.get('id'):
image.id = tag.get('id')
resource.add_resource(image.id, image)
return image
@Resource.register_factory('imageatlas')
def imageatlas_factory(resource, tag):
filename = resource.find_file(tag.get('file'))
if not filename:
raise ResourceError('No file= on <imageatlas> tag')
atlas = pyglet.image.load(filename)
atlas.properties = _handle_properties(tag)
if tag.get('id'):
atlas.id = tag.get('id')
resource.add_resource(atlas.id, atlas)
# figure default size if specified
if tag.get('size'):
d_width, d_height = map(int, tag.get('size').split('x'))
else:
d_width = d_height = None
for child in tag:
if child.tag != 'image':
raise ValueError, 'invalid child'
if child.get('size'):
width, height = map(int, child.get('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.get('offset').split(','))
image = atlas.get_region(x, y, width, height)
# set texture clamping to avoid mis-rendering subpixel edges
image.texture.id
glBindTexture(image.texture.target, image.texture.id)
glTexParameteri(image.texture.target,
GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
glTexParameteri(image.texture.target,
GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
# save the image off and set properties
id = child.get('id')
resource.add_resource(id, image)
image.properties = _handle_properties(child)
return atlas
#
# TILE SETS
#
@Resource.register_factory('tileset')
def tileset_factory(resource, tag):
id = tag.get('id')
properties = _handle_properties(tag)
tileset = TileSet(id, properties)
resource.add_resource(tileset.id, tileset)
for child in tag:
id = child.get('id')
offset = child.get('offset')
if offset:
offset = map(int, offset.split(','))
else:
offset = None
properties = _handle_properties(child)
image = child.find('image')
if image is not None:
image = resource.handle(image)
tile = Tile(id, properties, image, offset)
resource.add_resource(id, tile)
tileset[id] = tile
return tileset
class Tile(object):
'''Tiles hold an image and some optional properties.
'''
def __init__(self, id, properties, image, offset=None):
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)
class TileSet(dict):
'''Contains a set of Tile objects referenced by some id.
'''
def __init__(self, id, properties):
self.id = id
self.properties = properties
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.
Returns the Tile instance.
'''
if id is None:
id = self.generate_id()
self[id] = Tile(id, properties, image)
return self[id]
#
# RECT AND HEX MAPS
#
@Resource.register_factory('rectmap')
# TODO: more diagnostics for malformed files; by example when a columm has less
# cells than expected
def rectmap_factory(resource, tag):
width, height = map(int, tag.get('tile_size').split('x'))
origin = tag.get('origin')
if origin:
origin = map(int, tag.get('origin').split(','))
id = tag.get('id')
# now load the columns
cells = []
for i, column in enumerate(tag.getiterator('column')):
c = []
cells.append(c)
for j, cell in enumerate(column.getiterator('cell')):
tile = cell.get('tile')
if tile: tile = resource.get_resource(tile)
else: tile = None
properties = _handle_properties(cell)
c.append(RectCell(i, j, width, height, properties, tile))
properties = _handle_properties(tag)
m = RectMapLayer(id, width, height, cells, origin, properties)
resource.add_resource(id, m)
return m
@Resource.register_factory('hexmap')
def hexmap_factory(resource, tag):
height = int(tag.get('tile_height'))
width = hex_width(height)
origin = tag.get('origin')
if origin:
origin = map(int, tag.get('origin').split(','))
id = tag.get('id')
# now load the columns
cells = []
for i, column in enumerate(tag.getiterator('column')):
c = []
cells.append(c)
for j, cell in enumerate(column.getiterator('cell')):
tile = cell.get('tile')
if tile: tile = resource.get_resource(tile)
else: tile = None
properties = _handle_properties(tag)
c.append(HexCell(i, j, height, properties, tile))
properties = _handle_properties(tag)
m = HexMapLayer(id, width, cells, origin, properties)
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 MapLayer(layer.ScrollableLayer):
'''Base class for Maps.
Maps are comprised of tiles and can figure out which tiles are required to
be rendered on screen.
Both rect and hex maps have the following attributes:
id -- identifies the map in XML and Resources
(width, height) -- size of map in cells
(px_width, px_height) -- size of map in pixels
(tw, th) -- size of each cell in pixels
(origin_x, origin_y, origin_z) -- offset of map top left from origin in pixels
cells -- array [i][j] of Cell instances
debug -- display debugging information on cells
properties -- arbitrary properties
The debug flag turns on textual display of data about each visible cell
including its cell index, origin pixel and any properties set on the cell.
'''
def __init__(self, properties):
self._sprites = {}
self.properties = properties
super(MapLayer, self).__init__()
def __contains__(self, key):
return key in self.properties
def __getitem__(self, key):
if key in self.properties:
return self.properties[key]
raise KeyError(key)
def __setitem__(self, key, value):
self.properties[key] = value
def get(self, key, default=None):
return self.properties.get(key, default)
def set_dirty(self):
# re-calculate the sprites to draw for the view
self._sprites.clear()
self._update_sprite_set()
def set_view(self, x, y, w, h, viewport_x=0, viewport_y=0):
# invoked by ScrollingManager.set_focus()
super(MapLayer, self).set_view(x, y, w, h, viewport_x, viewport_y)
self._update_sprite_set()
def get_visible_cells(self):
'''Given the current view in map-space pixels, transform it based
on the current screen-space transform and figure the region of
map-space pixels currently visible.
Pass to get_in_region to return a list of Cell instances.
'''
# XXX refactor me away
x, y = self.view_x, self.view_y
w, h = self.view_w, self.view_h
return self.get_in_region(x, y, x + w, y + h)
def is_visible(self, rect):
'''Determine whether the indicated rect (with .x, .y, .width and
.height attributes) located in this Layer is visible.
'''
x, y = rect.x, rect.y
if x + rect.width < self.view_x: return False
if y + rect.height < self.view_y: return False
if x > self.view_x + self.view_w: return False
if y > self.view_y + self.view_h: return False
return True
debug = False
def set_debug(self, debug):
self.debug = debug
self._update_sprite_set()
def set_cell_opacity(self, i, j, opacity):
key = self.cells[i][j].origin[:2]
if key in self._sprites:
self._sprites[key].opacity = opacity
def set_cell_color(self, i, j, color):
key = self.cells[i][j].origin[:2]
if key in self._sprites:
self._sprites[key].color = color
def _update_sprite_set(self):
# update the sprites set
keep = set()
for cell in self.get_visible_cells():
cx, cy = key = cell.origin[:2]
keep.add(key)
if cell.tile is None:
continue
if key not in self._sprites:
self._sprites[key] = pyglet.sprite.Sprite(cell.tile.image,
x=cx, y=cy, batch=self.batch)
s = self._sprites[key]
if self.debug:
if getattr(s, '_label', None): continue
label = [
'cell=%d,%d'%(cell.i, cell.j),
'origin=%d,%d px'%(cx, cy),
]
for p in cell.properties:
label.append('%s=%r'%(p, cell.properties[p]))
lx, ly = cell.topleft
s._label = pyglet.text.Label(
'\n'.join(label), multiline=True, x=lx, y=ly,
bold=True, font_size=8, width=cell.width,
batch=self.batch)
else:
s._label = None
for k in list(self._sprites):
if k not in keep and k in self._sprites:
self._sprites[k]._label = None
del self._sprites[k]
class RegularTesselationMap(object):
'''A regularly tesselated map that allows access to its cells by index
(i, j).
'''
def get_cell(self, i, j):
''' Return Cell at cell pos=(i, j).
Return None if out of bounds.'''
if i < 0 or j < 0:
return None
try:
return self.cells[i][j]
except IndexError:
return None
class RectMap(RegularTesselationMap):
'''Rectangular map.
Cells are stored in column-major order with y increasing up,
allowing [i][j] addressing::
+---+---+---+
| d | e | f |
+---+---+---+
| a | b | c |
+---+---+---+
Thus cells = [['a', 'd'], ['b', 'e'], ['c', 'f']]
(and thus the cell at (0,0) is 'a' and (1, 1) is 'd')
'''
def __init__(self, id, tw, th, cells, origin=None, properties=None):
"""
:Parameters:
`id` : xml id
node id
`tw` : int
number of colums in cells
`th` : int
number of rows in cells
`cells` : container that supports cells[i][j]
elements are stored in column-major order with y increasing up
`origin` : (int, int, int)
cell block offset x,y,z ; default is (0,0,0)
`properties` : dict
arbitrary properties
if saving to XML, keys must be unicode or 8-bit ASCII strings
"""
self.properties = properties or {}
self.id = id
self.tw, self.th = tw, th
if origin is None:
origin = (0, 0, 0)
self.origin_x, self.origin_y, self.origin_z = origin
self.cells = cells
self.px_width = len(cells) * tw #? +abs(self.origin_x) ?
self.px_height = len(cells[0]) * th # +abs(self.origin_y) ?
def get_in_region(self, x1, y1, x2, y2):
'''Return cells (in [column][row]) that are within the map-space
pixel bounds specified by the bottom-left (x1, y1) and top-right
(x2, y2) corners.
Return a list of Cell instances.
'''
ox = self.origin_x
oy = self.origin_y
x1 = max(0, (x1 - ox) // self.tw)
y1 = max(0, (y1 - oy) // self.th)
x2 = min(len(self.cells), (x2 - ox) // self.tw + 1)
y2 = min(len(self.cells[0]), (y2 - oy) // self.th + 1)
## return [self.cells[i][j]
## for i in range(int(x1), int(x2))
## for j in range(int(y1), int(y2))]
res = [self.cells[i][j]
for i in range(int(x1), int(x2))
for j in range(int(y1), int(y2))]
#print 'get_in_region result:', res
return res
def get_at_pixel(self, x, y):
''' Return Cell at pixel px=(x,y) on the map.
The pixel coordinate passed in is in the map's coordinate space,
unmodified by screen, layer or view transformations.
Return None if out of bounds.
'''
return self.get_cell(int((x - self.origin_x) // self.tw),
int((y - self.origin_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.i + dx, cell.j + dy)
def get_neighbors(self, cell, diagonals=False):
'''Get all cells touching the sides of the nominated cell.
If "diagonals" is True then return the cells touching the corners
of this cell too.
Return a dict with the directions (self.UP, self.DOWN, etc) as keys
and neighbor cells as values.
'''
r = {}
if diagonals:
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
if dx or dy:
direction = (dx, dy)
r[direction] = self.get_cell(cell.i + dx, cell.j + dy)
else:
for direction in (self.UP, self.RIGHT, self.LEFT, self.DOWN):
dx, dy = direction
r[direction] = self.get_cell(cell.i + dx, cell.j + dy)
return r
# TODO: add checks to ensure good html. By example, what if cell is None?
def _as_xml(self, root):
"""stores a XML representation of itself as child of root with type rectmap
"""
m = ElementTree.SubElement(root, 'rectmap', id=self.id,
tile_size='%dx%d'%(self.tw, self.th),
origin='%s,%s,%s'%(self.origin_x, self.origin_y, self.origin_z))
m.tail = '\n'
# map properties
for k in self.properties:
v = self.properties[k]
t = type(v)
v = _python_to_xml[t](v)
p = ElementTree.SubElement(m, 'property', name=k, value=v,
type=_xml_type[t])
p.tail = '\n'
# columns / cells
for column in self.cells:
c = ElementTree.SubElement(m, 'column')
c.tail = '\n'
for cell in column:
cell._as_xml(c)
class RectMapLayer(RectMap, MapLayer):
'''A renderable, scrollable rect map.
'''
def __init__(self, id, tw, th, cells, origin=None, properties=None):
RectMap.__init__(self, id, tw, th, cells, origin, properties)
MapLayer.__init__(self, properties)
class RectMapCollider(object):
'''This class implements collisions between a moving rect object and a
tilemap.
'''
def collide_bottom(self, dy):
pass
def collide_left(self, dx):
pass
def collide_right(self, dx):
pass
def collide_top(self, dy):
pass
def collide_map(self, map, last, new, dy, dx):
'''Collide a rect with the given RectMap map.
Apart from "map" the arguments are as per `do_collision`.
'''
tested = set()
for cell in map.get_in_region(*(new.bottomleft + new.topright)):
if cell is None or cell.tile is None:
continue
# don't re-test
key = (cell.i, cell.j)
if key in tested:
continue
tested.add(cell)
self.do_collision(cell, last, new, dy, dx)
# resolve them and re-collide if necessary; make sure the cells
# colliding the sprite midpoints are done first
def do_collision(self, cell, last, new, dy, dx):
'''Collide a Rect moving from "last" to "new" with the given map
RectCell "cell". The "dx" and "dy" values may indicate the velocity
of the moving rect.
The RectCell must have the boolean properties "top", "left",
"bottom" and "right" for those sides which the rect should collide.
If there is no collision then nothing is done.
If there is a collision:
1. The "new" rect's position will be modified to its closest position
to the side of the cell that the collision is on, and
2. If the "dx" and "dy" values are passed in the methods
collide_<side> will be called to indicate that the rect has
collided with the cell on the rect's side indicated. The value
passed to the collide method will be a *modified* distance based
on the position of the rect after collision (according to step
#1).
'''
g = cell.tile.properties.get
self.resting = False
if (g('top') and last.bottom >= cell.top and new.bottom < cell.top):
dy = last.y - new.y
new.bottom = cell.top
if dy: self.collide_bottom(dy)
if (g('left') and last.right <= cell.left and new.right > cell.left):
dx = last.x - new.x
new.right = cell.left
if dx: self.collide_right(dx)
if (g('right') and last.left >= cell.right and new.left < cell.right):
dx = last.x - new.x
new.left = cell.right
if dx: self.collide_left(dx)
self.dx = 0
if (g('bottom') and last.top <= cell.bottom and new.top > cell.bottom):
dy = last.y - new.y
new.top = cell.bottom
if dy: self.collide_top(dy)
class Cell(object):
'''Base class for cells from rect and hex maps.
Common attributes:
i, j -- index of this cell in the map
position -- the above as a tuple
width, height -- dimensions
properties -- arbitrary properties
cell -- cell from the MapLayer's cells
Properties are available through the dictionary interface, ie. if the
cell has a property 'cost' then you may access it as:
cell['cost']
You may also set properties in this way and use the .get() method to
supply a default value.
If the named property does not exist on the cell it will be looked up
on the cell's tile.
'''
def __init__(self, i, j, width, height, properties, tile):
self.width, self.height = width, height
self.i, self.j = i, j
self.properties = properties
self.tile = tile
@property
def position(self): return (self.i, self.j)
def _as_xml(self, parent):
c = ElementTree.SubElement(parent, 'cell')
c.tail = '\n'
if self.tile:
c.set('tile', self.tile.id)
for k in self.properties:
v = self.properties[k]
t = type(v)
v = _python_to_xml[t](v)
ElementTree.SubElement(c, 'property', name=k, value=v,
type=_xml_type[t])
def __contains__(self, key):
if key in self.properties:
return True
return key in self.tile.properties
def __getitem__(self, key):
if key in self.properties:
return self.properties[key]
elif self.tile is not None and key in self.tile.properties:
return self.tile.properties[key]
raise KeyError(key)
def __setitem__(self, key, value):
self.properties[key] = value
def get(self, key, default=None):
if key in self.properties:
return self.properties[key]
if self.tile is None:
return default
return self.tile.properties.get(key, default)
def __repr__(self):
return '<%s object at 0x%x (%g, %g) properties=%r tile=%r>'%(
self.__class__.__name__, id(self), self.i, self.j,
self.properties, self.tile)
class RectCell(Rect, Cell):
'''A rectangular cell from a MapLayer.
Cell attributes:
i, j -- index of this cell in the map
x, y -- bottom-left pixel
width, height -- dimensions
properties -- arbitrary properties
cell -- cell from the MapLayer's cells
The cell may have the standard properties "top", "left", "bottom" and
"right" which are booleans indicating that those sides are impassable.
These are used by RectCellCollider.
Note that all pixel attributes are *not* adjusted for screen,
view or layer transformations.
'''
def __init__(self, i, j, width, height, properties, tile):
Rect.__init__(self, i*width, j*height, width, height)
Cell.__init__(self, i, j, width, height, properties, tile)
# other properties are read-only
origin = property(Rect.get_origin)
top = property(Rect.get_top)
bottom = property(Rect.get_bottom)
center = property(Rect.get_center)
midtop = property(Rect.get_midtop)
midbottom = property(Rect.get_midbottom)
left = property(Rect.get_left)
right = property(Rect.get_right)
topleft = property(Rect.get_topleft)
topright = property(Rect.get_topright)
bottomleft = property(Rect.get_bottomleft)
bottomright = property(Rect.get_bottomright)
midleft = property(Rect.get_midleft)
midright = property(Rect.get_midright)
class HexMap(RegularTesselationMap):
'''MapLayer with flat-top, regular hexagonal cells.
Calculated attributes:
edge_length -- length of an edge in pixels = int(th / math.sqrt(3))
tw -- with of a "tile" in pixels = edge_length * 2
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']]
(and this the cell at (0, 0) is 'a' and (1, 1) is 'd')
'''
def __init__(self, id, th, cells, origin=None, properties=None):
properties = properties or {}
self.id = id
self.th = th
if origin is None:
origin = (0, 0, 0)
self.origin_x, self.origin_y, self.origin_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.px_width = self.tw + (width - 1) * (s + s // 2)
self.px_height = height * self.th
if not width % 2:
self.px_height += (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[i][j] for i in range(x1, x2) for j in range(y1, y2)]
# XXX add get_from_screen
def get_at_pixel(self, x, y):
'''Get the Cell at pixel (x,y).
Return None if out of bounds.'''
print 'LOOKING UP', (x, y), 'with edge_length', self.edge_length
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)
print 'x=', x
y = y // self.th
print 'y=', y
if x % 2:
# every second cell is up one
y -= self.th // 2
print 'shift y=', y
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.i, cell.j + 1)
elif direction is self.DOWN:
return self.get_cell(cell.i, cell.j - 1)
elif direction is self.UP_LEFT:
if cell.i % 2:
return self.get_cell(cell.i - 1, cell.j + 1)
else:
return self.get_cell(cell.i - 1, cell.j)
elif direction is self.UP_RIGHT:
if cell.i % 2:
return self.get_cell(cell.i + 1, cell.j + 1)
else:
return self.get_cell(cell.i + 1, cell.j)
elif direction is self.DOWN_LEFT:
if cell.i % 2:
return self.get_cell(cell.i - 1, cell.j)
else:
return self.get_cell(cell.i - 1, cell.j - 1)
elif direction is self.DOWN_RIGHT:
if cell.i % 2:
return self.get_cell(cell.i + 1, cell.j)
else:
return self.get_cell(cell.i + 1, cell.j - 1)
else:
raise ValueError, 'Unknown direction %r'%direction
def get_neighbors(self, cell):
'''Get all neighbor cells for the nominated cell.
Return a dict with the directions (self.UP, self.DOWN, etc) as keys
and neighbor cells as values.
'''
r = {}
for direction in (self.UP_LEFT, self.UP, self.UP_RIGHT,
self.DOWN_LEFT, self.DOWN, self.DOWN_RIGHT):
dx, dy = direction
r[direction] = self.get_cell(cell.i + dx, cell.j + dy)
return r
class HexMapLayer(HexMap, MapLayer):
'''A renderable, scrollable hex map.
The Layer has a calculated attribute:
edge_length -- length of an edge in pixels = int(th / math.sqrt(3))
tw -- with of a "tile" in pixels = edge_length * 2
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, properties=None):
HexMap.__init__(self, id, th, cells, origin, properties)
HexMapLayer.__init__(self, properties)
# 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.
Cell attributes:
i, j -- index of this cell in the map
width, height -- dimensions
properties -- arbitrary properties
cell -- cell from the MapLayer's cells
Read-only attributes:
x, y -- bottom-left pixel
top -- y pixel extent
bottom -- y pixel extent
left -- (x, y) of left corner pixel
right -- (x, y) of right corner pixel
center -- (x, y)
origin -- (x, y) of bottom-left corner of bounding rect
topleft -- (x, y) of top-left corner pixel
topright -- (x, y) of top-right corner pixel
bottomleft -- (x, y) of bottom-left corner pixel
bottomright -- (x, y) of bottom-right corner pixel
midtop -- (x, y) of middle of top side pixel
midbottom -- (x, y) of middle of bottom side pixel
midtopleft -- (x, y) of middle of left side pixel
midtopright -- (x, y) of middle of right side pixel
midbottomleft -- (x, y) of middle of left side pixel
midbottomright -- (x, y) of middle of right side pixel
Note that all pixel attributes are *not* adjusted for screen,
view or layer transformations.
'''
def __init__(self, i, j, height, properties, tile):
width = hex_width(height)
Cell.__init__(self, i, j, width, height, properties, tile)
def get_origin(self):
x = self.i * (self.width / 2 + self.width // 4)
y = self.j * self.height
if self.i % 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 |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Batch
Batches
=======
Batches allow you to optimize the number of gl calls using pyglets batch
"""
__docformat__ = 'restructuredtext'
import cocosnode
from batch import *
import pyglet
from pyglet.graphics import OrderedGroup
from pyglet import image
from pyglet.gl import *
__all__ = ['BatchNode','BatchableNode']
def ensure_batcheable(node):
if not isinstance(node, BatchableNode):
raise Exception("Children node of a batch must be have the batch mixin")
for c in node.get_children():
ensure_batcheable(c)
class BatchNode( cocosnode.CocosNode ):
def __init__(self):
super(BatchNode, self).__init__()
self.batch = pyglet.graphics.Batch()
self.groups = {}
def add(self, child, z=0, name=None):
ensure_batcheable(child)
child.set_batch(self.batch, self.groups, z)
super(BatchNode, self).add(child, z, name)
def visit(self):
""" All children are placed in to self.batch, so nothing to visit """
glPushMatrix()
self.transform()
self.batch.draw()
glPopMatrix()
def remove(self, child):
if isinstance(child, str):
child_node = self.get(child)
else:
child_node = child
child_node.set_batch(None)
super(BatchNode, self).remove(child)
def draw(self):
pass # All drawing done in visit!
class BatchableNode( cocosnode.CocosNode ):
def add(self, child, z=0, name=None):
batchnode = self.get_ancestor(BatchNode)
if not batchnode:
# this node was addded, but theres no batchnode in the
# hierarchy. so we proceed as normal
super(BatchableNode, self).add(child, z, name)
return
ensure_batcheable(child)
super(BatchableNode, self).add(child, z, name)
child.set_batch(self.batch, batchnode.groups, z)
def remove(self, child):
if isinstance(child, str):
child_node = self.get(child)
else:
child_node = child
child_node.set_batch(None)
super(BatchableNode, self).remove(child)
def set_batch(self, batch, groups=None, z=0):
self.batch = batch
if batch is None:
self.group = None
else:
group = groups.get(z)
if group is None:
group = pyglet.graphics.Group()
groups[z] = group
self.group = group
for childZ, child in self.children:
child.set_batch(self.batch, groups, z + childZ)
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Text cocos nodes
'''
__docformat__ = 'restructuredtext'
from director import director
import cocosnode
from batch import *
import pyglet
from pyglet.graphics import OrderedGroup
from pyglet import image
from pyglet.gl import *
from batch import *
class TextElement(cocosnode.CocosNode):
"""
Base class for all cocos text
Provides the CocosNode interfase and a pyglet Batch to store parts
"""
def __init__(self, text='', position=(0,0), **kwargs):
super(TextElement, self).__init__()
self.position = position
self.args = []
self.kwargs = kwargs
kwargs['text']=text
self.group = None
self.batch = None
self.batch = pyglet.graphics.Batch()
self.create_element()
def create_element(self):
self.element = self.klass(group=self.group, batch=self.batch, **self.kwargs)
def draw(self):
glPushMatrix()
self.transform()
self.element.draw()
glPopMatrix()
def _get_opacity(self):
return self.element.color[3]
def _set_opacity(self, value):
self.element.color = tuple(self.element.color[:3]) + (int(value),)
opacity = property(_get_opacity, _set_opacity)
class Label(TextElement):
'''CocosNode Label element. It is a wrapper of pyglet.text.Label with the benefits
of being of a CocosNode
'''
klass = pyglet.text.Label
class HTMLLabel(TextElement):
'''CocosNode HTMLLabel element. It is a wrapper of pyglet.text.HTMLLabel with the benefits
of being of a CocosNode
'''
klass = pyglet.text.HTMLLabel
class PygletRichLabel(pyglet.text.DocumentLabel):
'''Rich text label.
'''
def __init__(self, text='',
font_name=None, font_size=None, bold=False, italic=False,
color=None,
x=0, y=0, width=None, height=None,
anchor_x='left', anchor_y='baseline',
halign='left',
multiline=False, dpi=None, batch=None, group=None):
'''Create a rich text label.
:Parameters:
`text` : str
Pyglet attributed (rich) text to display.
`font_name` : str or list
Font family name(s). If more than one name is given, the
first matching name is used.
`font_size` : float
Font size, in points.
`bold` : bool
Bold font style.
`italic` : bool
Italic font style.
`color` : (int, int, int, int) or None
Font colour, as RGBA components in range [0, 255].
None to use font colors defined by text attributes.
`x` : int
X coordinate of the label.
`y` : int
Y coordinate of the label.
`width` : int
Width of the label in pixels, or None
`height` : int
Height of the label in pixels, or None
`anchor_x` : str
Anchor point of the X coordinate: one of ``"left"``,
``"center"`` or ``"right"``.
`anchor_y` : str
Anchor point of the Y coordinate: one of ``"bottom"``,
``"baseline"``, ``"center"`` or ``"top"``.
`halign` : str
Horizontal alignment of text on a line, only applies if
a width is supplied. One of ``"left"``, ``"center"``
or ``"right"``.
`multiline` : bool
If True, the label will be word-wrapped and accept newline
characters. You must also set the width of the label.
`dpi` : float
Resolution of the fonts in this layout. Defaults to 96.
`batch` : `Batch`
Optional graphics batch to add the label to.
`group` : `Group`
Optional graphics group to use.
'''
text = '{color (255, 255, 255, 255)}' + text
document = pyglet.text.decode_attributed(text)
super(PygletRichLabel, self).__init__(document, x, y, width, height,
anchor_x, anchor_y,
multiline, dpi, batch, group)
style = dict(halign=halign)
if font_name:
style['font_name'] = font_name
if font_size:
style['font_size'] = font_size
if bold:
style['bold'] = bold
if italic:
style['italic'] = italic
if color:
style['color'] = color
self.document.set_style(0, len(self.document.text), style)
class RichLabel(TextElement):
'''CocosNode RichLabel element. It is a wrapper of a custom Pyglet Rich Label
using rich text attributes with the benefits of being of a CocosNode
'''
klass = PygletRichLabel
| 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=0, y=0):
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 __neq__(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):
# Vector + Vector -> Vector
# Vector + Point -> Point
# Point + Point -> Vector
if self.__class__ is other.__class__:
_class = Vector2
else:
_class = Point2
return _class(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):
# Vector - Vector -> Vector
# Vector - Point -> Point
# Point - Point -> Vector
if self.__class__ is other.__class__:
_class = Vector2
else:
_class = Point2
return _class(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[0] - self.x,
other[1] - self.y)
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=0, y=0, z=0):
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 __neq__(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[0] - self.x,
other[1] - self.y,
other[2] - self.z)
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)
# 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)
def determinant(self):
m00 = self.a
m10 = self.b
m20 = self.c
m01 = self.e
m11 = self.f
m21 = self.g
m02 = self.i
m12 = self.j
m22 = self.k
return m00*m11*m22 + m01*m12*m20 + m02*m10*m21 - m00*m12*m21 - m01*m10*m22 - m02*m11*m20
def inverse(self):
tmp = Matrix3()
det = self.determinant()
if abs(det) < 0.001:
# No inverse, return identity
return tmp
else:
m00 = self.a
m10 = self.b
m20 = self.c
m01 = self.e
m11 = self.f
m21 = self.g
m02 = self.i
m12 = self.j
m22 = self.k
det = 1.0 / det
tmp.a = det * (m11*m22 - m12*m21)
tmp.b = det * (m12*m20 - m10*m22)
tmp.c = det * (m10*m21 - m11*m20)
tmp.e = det * (m02*m21 - m01*m22)
tmp.f = det * (m00*m22 - m02*m20)
tmp.g = det * (m01*m20 - m00*m21)
tmp.i = det * (m01*m12 - m02*m11)
tmp.j = det * (m02*m10 - m00*m12)
tmp.k = det * (m00*m11 - m01*m10)
return tmp
# 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):
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, 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 transform(self, other):
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
w = A.m * B.x + A.n * B.y + A.o * B.z + A.p
if w != 0:
P.x /= w
P.y /= w
P.z /= w
return P
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
def rotate_triple_axis(self, x, y, z):
self *= Matrix4.new_rotate_triple_axis(x, y, z)
return self
def transpose(self):
(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) = \
(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 transposed(self):
M = self.copy()
M.transpose()
return M
# Static constructors
def new(cls, *values):
M = cls()
M[:] = values
return M
new = classmethod(new)
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_rotate_triple_axis(cls, x, y, z):
m = cls()
m.a, m.b, m.c = x.x, y.x, z.x
m.e, m.f, m.g = x.y, y.y, z.y
m.i, m.j, m.k = x.z, y.z, z.z
return m
new_rotate_triple_axis = classmethod(new_rotate_triple_axis)
def new_look_at(cls, eye, at, up):
z = (eye - at).normalized()
x = up.cross(z).normalized()
y = z.cross(x)
m = cls.new_rotate_triple_axis(x, y, z)
m.d, m.h, m.l = eye.x, eye.y, eye.z
return m
new_look_at = classmethod(new_look_at)
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)
def determinant(self):
return ((self.a * self.f - self.e * self.b)
* (self.k * self.p - self.o * self.l)
- (self.a * self.j - self.i * self.b)
* (self.g * self.p - self.o * self.h)
+ (self.a * self.n - self.m * self.b)
* (self.g * self.l - self.k * self.h)
+ (self.e * self.j - self.i * self.f)
* (self.c * self.p - self.o * self.d)
- (self.e * self.n - self.m * self.f)
* (self.c * self.l - self.k * self.d)
+ (self.i * self.n - self.m * self.j)
* (self.c * self.h - self.g * self.d))
def inverse(self):
tmp = Matrix4()
d = self.determinant();
if abs(d) < 0.001:
# No inverse, return identity
return tmp
else:
d = 1.0 / d;
tmp.a = d * (self.f * (self.k * self.p - self.o * self.l) + self.j * (self.o * self.h - self.g * self.p) + self.n * (self.g * self.l - self.k * self.h));
tmp.e = d * (self.g * (self.i * self.p - self.m * self.l) + self.k * (self.m * self.h - self.e * self.p) + self.o * (self.e * self.l - self.i * self.h));
tmp.i = d * (self.h * (self.i * self.n - self.m * self.j) + self.l * (self.m * self.f - self.e * self.n) + self.p * (self.e * self.j - self.i * self.f));
tmp.m = d * (self.e * (self.n * self.k - self.j * self.o) + self.i * (self.f * self.o - self.n * self.g) + self.m * (self.j * self.g - self.f * self.k));
tmp.b = d * (self.j * (self.c * self.p - self.o * self.d) + self.n * (self.k * self.d - self.c * self.l) + self.b * (self.o * self.l - self.k * self.p));
tmp.f = d * (self.k * (self.a * self.p - self.m * self.d) + self.o * (self.i * self.d - self.a * self.l) + self.c * (self.m * self.l - self.i * self.p));
tmp.j = d * (self.l * (self.a * self.n - self.m * self.b) + self.p * (self.i * self.b - self.a * self.j) + self.d * (self.m * self.j - self.i * self.n));
tmp.n = d * (self.i * (self.n * self.c - self.b * self.o) + self.m * (self.b * self.k - self.j * self.c) + self.a * (self.j * self.o - self.n * self.k));
tmp.c = d * (self.n * (self.c * self.h - self.g * self.d) + self.b * (self.g * self.p - self.o * self.h) + self.f * (self.o * self.d - self.c * self.p));
tmp.g = d * (self.o * (self.a * self.h - self.e * self.d) + self.c * (self.e * self.p - self.m * self.h) + self.g * (self.m * self.d - self.a * self.p));
tmp.k = d * (self.p * (self.a * self.f - self.e * self.b) + self.d * (self.e * self.n - self.m * self.f) + self.h * (self.m * self.b - self.a * self.n));
tmp.o = d * (self.m * (self.f * self.c - self.b * self.g) + self.a * (self.n * self.g - self.f * self.o) + self.e * (self.b * self.o - self.n * self.c));
tmp.d = d * (self.b * (self.k * self.h - self.g * self.l) + self.f * (self.c * self.l - self.k * self.d) + self.j * (self.g * self.d - self.c * self.h));
tmp.h = d * (self.c * (self.i * self.h - self.e * self.l) + self.g * (self.a * self.l - self.i * self.d) + self.k * (self.e * self.d - self.a * self.h));
tmp.l = d * (self.d * (self.i * self.f - self.e * self.j) + self.h * (self.a * self.j - self.i * self.b) + self.l * (self.e * self.b - self.a * self.f));
tmp.p = d * (self.a * (self.f * self.k - self.j * self.g) + self.e * (self.j * self.c - self.b * self.k) + self.i * (self.b * self.g - self.f * self.c));
return tmp;
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, w=1, x=0, y=0, z=0):
self.w = w
self.x = x
self.y = y
self.z = z
def __copy__(self):
Q = Quaternion()
Q.w = self.w
Q.x = self.x
Q.y = self.y
Q.z = self.z
return Q
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 rotate_matrix(self, m):
self *= Quaternion.new_rotate_matrix(m)
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 = self.w / d
Q.x = self.x / d
Q.y = self.y / d
Q.z = self.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_rotate_matrix(cls, m):
if m[0*4 + 0] + m[1*4 + 1] + m[2*4 + 2] > 0.00000001:
t = m[0*4 + 0] + m[1*4 + 1] + m[2*4 + 2] + 1.0
s = 0.5/math.sqrt(t)
return cls(
s*t,
(m[1*4 + 2] - m[2*4 + 1])*s,
(m[2*4 + 0] - m[0*4 + 2])*s,
(m[0*4 + 1] - m[1*4 + 0])*s
)
elif m[0*4 + 0] > m[1*4 + 1] and m[0*4 + 0] > m[2*4 + 2]:
t = m[0*4 + 0] - m[1*4 + 1] - m[2*4 + 2] + 1.0
s = 0.5/math.sqrt(t)
return cls(
(m[1*4 + 2] - m[2*4 + 1])*s,
s*t,
(m[0*4 + 1] + m[1*4 + 0])*s,
(m[2*4 + 0] + m[0*4 + 2])*s
)
elif m[1*4 + 1] > m[2*4 + 2]:
t = -m[0*4 + 0] + m[1*4 + 1] - m[2*4 + 2] + 1.0
s = 0.5/math.sqrt(t)
return cls(
(m[2*4 + 0] - m[0*4 + 2])*s,
(m[0*4 + 1] + m[1*4 + 0])*s,
s*t,
(m[1*4 + 2] + m[2*4 + 1])*s
)
else:
t = -m[0*4 + 0] - m[1*4 + 1] + m[2*4 + 2] + 1.0
s = 0.5/math.sqrt(t)
return cls(
(m[0*4 + 1] - m[1*4 + 0])*s,
(m[2*4 + 0] + m[0*4 + 2])*s,
(m[1*4 + 2] + m[2*4 + 1])*s,
s*t
)
new_rotate_matrix = classmethod(new_rotate_matrix)
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
if costheta < 0.:
costheta = -costheta
q1 = q1.conjugated()
elif costheta > 1:
costheta = 1
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)
# Tangent
if u1 == u2:
return Point2(L.p.x + u1 * L.v.x,
L.p.y + u1 * L.v.y)
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 |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''a framework for building 2D games, demos, and other graphical/interactive applications.
Main Features
-------------
* Flow control: Manage the flow control between different scenes in an easy way
* Sprites: Fast and easy sprites
* Actions: Just tell sprites what you want them to do. Composable actions like move, rotate, scale and much more
* Effects: Effects like waves, twirl, lens and much more
* Tiled Maps: Support for rectangular and hexagonal tiled maps
* Transitions: Move from scene to scene with style
* Menus: Built in classes to create menus
* Text Rendering: Label and HTMLLabel with action support
* Documentation: Programming Guide + API Reference + Video Tutorials + Lots of simple tests showing how to use it
* Built-in Python Interpreter: For debugging purposes
* BSD License: Just use it
* Pyglet Based: No external dependencies
* OpenGL Based: Hardware Acceleration
http://cocos2d.org
'''
__docformat__ = 'restructuredtext'
__version__ = "0.4rc0"
__author__ = "cocos2d team"
version = __version__
import sys
# add the cocos resources path
import os, pyglet
pyglet.resource.path.append(
os.path.join(os.path.dirname(os.path.realpath(__file__)), "resources")
)
pyglet.resource.reindex()
try:
unittesting = os.environ['cocos_utest']
except KeyError:
unittesting = False
del os, pyglet
# in windows we use the pygame package to get the SDL dlls
# we must get the path here because the inner pygame module will hide the real
if sys.platform == 'win32':
import imp
try:
dummy, sdl_lib_path, dummy = imp.find_module('pygame')
del dummy
except ImportError:
sdl_lib_path = None
def import_all():
import actions
import director
import layer
import menu
import sprite
import path
import scene
import grid
import text
import camera
import draw
import skeleton
import rect
import tiles
if not unittesting:
import_all()
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
import math
import cPickle
import cocos
from cocos import euclid
import pyglet
from pyglet.gl import *
import copy
class Skin(cocos.cocosnode.CocosNode):
def __init__(self, skeleton):
super(Skin, self).__init__()
self.skeleton = skeleton
class ColorSkin(Skin):
def __init__(self, skeleton, color):
super(ColorSkin, self).__init__(skeleton)
self.color = color
def draw(self):
self.skeleton.propagate_matrix()
glPushMatrix()
self.transform()
self.skeleton.visit_children( lambda bone: self.draw_bone( bone ) )
bones = self.skeleton.visit_children(
lambda bone: (bone.label, bone.parent_matrix*bone.matrix))
bones = dict(bones)
glPopMatrix()
def draw_bone(self, bone):
p1 = bone.get_start()
p2 = bone.get_end()
glColor4ub(*self.color)
glLineWidth(5)
glBegin(GL_LINES)
glVertex2f(*p1)
glVertex2f(*p2)
glEnd()
class BitmapSkin(Skin):
skin_parts = []
def __init__(self, skeleton, skin_def, alpha=255):
super(BitmapSkin, self).__init__(skeleton)
self.alpha = alpha
self.skin_parts = skin_def
self.regenerate()
def move(self, idx, dx, dy):
sp = self.skin_parts
pos = sp[idx][1]
sp[idx] = sp[idx][0], (pos[0]+dx, pos[1]+dy), sp[idx][2], \
sp[idx][3], sp[idx][4], sp[idx][5]
self.regenerate()
def get_control_points(self):
return [ (i, p[0]) for i,p in enumerate(self.skin_parts) ]
def regenerate(self):
# print self.skin_parts
self.parts = [ (name, position, scale,\
pyglet.resource.image(image,flip_y=flip_y, flip_x=flip_x)) \
for name, position, image, flip_x, flip_y, scale
in self.skin_parts ]
def draw(self):
self.skeleton.propagate_matrix()
glPushMatrix()
self.transform()
bones = self.skeleton.visit_children(
lambda bone: (bone.label, bone.parent_matrix*bone.matrix))
bones = dict(bones)
for bname, position, scale, image in self.parts:
matrix = bones[bname]
self.blit_image(matrix, position, scale, image)
glPopMatrix()
def blit_image(self, matrix, position, scale, image):
x, y = image.width*scale, image.height*scale
#dx = self.x + position[0]
#dy = self.y + position[1]
dx, dy = position
glEnable(image.target)
glBindTexture(image.target, image.id)
glPushAttrib(GL_COLOR_BUFFER_BIT)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
# blit img
points = [
(-dx, -dy),
(x-dx, -dy),
(x-dx, y-dy),
(-dx, y-dy)
]
a,b,_,c,d,_,e,f,_,g,h,_ = image.texture.tex_coords
textures = [ a,b,c,d,e,f,g,h ]
np = [ matrix*euclid.Point2(*p) for p in points ]
glColor4ub(255,255,255,self.alpha)
glBegin(GL_QUADS)
glTexCoord2f(a,b)
glVertex2f(*np[0])
glTexCoord2f(c,d)
glVertex2f(*np[1])
glTexCoord2f(e,f)
glVertex2f(*np[2])
glTexCoord2f(g,h)
glVertex2f(*np[3])
glEnd()
glColor4ub(255,255,255,255)
#pyglet.graphics.draw(4, GL_QUADS,
# ("v2f", new_points),
# ("t2f", textures),
# ("c4B", [255,255,255,self.alpha]*4),
# )
glPopAttrib()
glDisable(image.target)
def flip(self):
nsp = []
for name, position, image, flip_x, flip_y, scale in self.skin_parts:
im = pyglet.resource.image(image,flip_y=flip_y, flip_x=flip_x)
x = im.width*scale - position[0]
y = position[1]
nsp.append( (name, (x,y), image, not flip_x, flip_y, scale))
self.skin_parts = nsp
self.regenerate()
self.skeleton = self.skeleton.flipped()
class Animate(cocos.actions.IntervalAction):
def init(self, animation, recenter=False, recenter_x=False, recenter_y=False):
if recenter:
recenter_x = recenter_y = True
self.recenter_x = recenter_x
self.recenter_y = recenter_y
self.duration = animation.get_duration()
self.animation = animation
def start(self):
nsk = copy.deepcopy(self.target.skeleton)
if self.recenter_x:
self.target.x += nsk.translation.x
nsk.translation.x = 0
if self.recenter_y:
self.target.y += nsk.translation.y
nsk.translation.y = 0
self.start_skeleton = nsk
def update(self, t):
self.animation.pose(self.target.skeleton, t, self.start_skeleton)
def __reversed__(self):
raise NotImplementedError("gimme some time")
class Skeleton(object):
def __init__(self, bone):
super(Skeleton, self).__init__()
self.bone = bone
self.matrix = euclid.Matrix3.new_identity()
self.translation = euclid.Vector2(0,0)
def flipped(self):
sk = Skeleton(self.bone.flipped())
sk.translation.x = -self.translation.x
sk.translation.y = self.translation.y
sk.matrix = euclid.Matrix3.new_translate( *sk.translation )
return sk
def save(self, name):
f = open(name, "w")
cPickle.dump(self, f)
f.close()
def move(self, dx, dy):
self.matrix.translate(dx, dy)
self.translation.x += dx
self.translation.y += dy
def propagate_matrix(self):
def visit(matrix, child):
child.parent_matrix = matrix
matrix = matrix * child.matrix
for c in child.children:
visit(matrix, c)
visit(self.matrix, self.bone)
def visit_children(self, func):
result = []
def inner(bone):
result.append( func( bone ) )
for b in bone.children:
inner(b)
inner(self.bone)
return result
def get_control_points(self):
points = [self]
self.propagate_matrix()
points += self.visit_children( lambda bone: bone )
return points
def interpolated_to(self, next, delta):
sk = Skeleton(self.bone.interpolated_to(next.bone, delta))
sk.translation = (next.translation-self.translation) * delta + self.translation
sk.matrix = euclid.Matrix3.new_translate( *sk.translation )
return sk
def pose_from(self, other):
self.matrix = other.matrix
self.translation = other.translation
self.bone = copy.deepcopy(other.bone)
class Bone(object):
def __init__(self, label, size, rotation, translation):
self.size = size
self.label = label
self.children = []
self.matrix = euclid.Matrix3.new_translate(*translation) * \
euclid.Matrix3.new_rotate( math.radians(rotation) )
self.parent_matrix = euclid.Matrix3.new_identity()
self.translation = euclid.Point2(*translation)
self.rotation = math.radians(rotation)
def move(self, dx, dy):
self.translation.x += dx
self.translation.y += dy
self.matrix = euclid.Matrix3.new_translate(*self.translation) * \
euclid.Matrix3.new_rotate( self.rotation)
def flipped(self):
bone = Bone(self.label, self.size, -math.degrees(self.rotation),
(-self.translation[0], self.translation[1]))
for b in self.children:
bone.add( b.flipped() )
return bone
def rotate(self, angle):
self.rotation += angle
self.matrix.rotate( angle )
def add(self, bone):
self.children.append(bone)
return self
def get_end(self):
return self.parent_matrix * self.matrix * euclid.Point2(0, -self.size)
def get_start(self):
return self.parent_matrix * self.matrix * euclid.Point2(0, 0)
def interpolated_to(self, next, delta):
ea = next.rotation%(math.pi*2)
sa = self.rotation %(math.pi*2)
angle = ((ea%(math.pi*2)) - (sa%(math.pi*2)))
if angle > math.pi:
angle = -math.pi*2+angle
if angle < -math.pi:
angle = math.pi*2+angle
nr = ( sa + angle * delta ) % (math.pi*2)
nr = math.degrees( nr )
bone = Bone(self.label, self.size, nr, self.translation)
for i, c in enumerate(self.children):
nc = c.interpolated_to(next.children[i], delta)
bone.add( nc )
return bone
def dump(self, depth=0):
print "-"*depth, self
for c in self.children:
c.dump(depth+1)
def repr(self, depth=0):
repr = " "*depth*4 + "Bone('%s', %s, %s, %s)"%(
self.label, self.size, math.degrees(self.rotation), self.translation
)
for c in self.children:
repr += " "*depth*4 +".add(\n" + c.repr(depth+1) + ")"
repr += "\n"
return repr
class Animation(object):
def __init__(self, skeleton):
self.frames = {}
self.position = 0
self.skeleton = skeleton
def flipped(self):
c = copy.deepcopy(self)
for t, sk in c.frames.items():
c.frames[t] = sk.flipped()
return c
def pose(self, who, t, start):
dt = t * self.get_duration()
self.position = dt
ct, curr = self.get_keyframe()
#print who.tranlation
# if we are in a keyframe, pose that
if curr:
who.pose_from( curr )
return
# find previous, if not, use start
pt, prev = self.get_keyframe(-1)
if not prev:
prev = start
pt = 0
# find next, if not, pose at prev
nt, next = self.get_keyframe(1)
if not next:
who.pose_from( prev )
return
# we find the dt betwen prev and next and pose from it
ft = (nt-dt)/(nt-pt)
who.pose_from( next.interpolated_to( prev, ft ) )
def get_duration(self):
if self.frames:
return max(max( self.frames ), self.position )
else:
return self.position
def get_markers(self):
return self.frames.keys()
def get_position(self):
return self.position
def get_keyframe(self, offset=0):
if offset == 0:
if self.position in self.frames:
return self.position, self.frames[self.position]
else:
return None, None
elif offset < 0:
prevs = [ t for t in self.frames if t < self.position ]
prevs.sort()
if abs(offset) <= len(prevs):
return prevs[offset], self.frames[prevs[offset]]
else:
return None, None
elif offset > 0:
next = [ t for t in self.frames if t > self.position ]
next.sort()
if abs(offset) <= len(next):
return next[offset-1], self.frames[next[offset-1]]
else:
return None, None
def next_keyframe(self):
next = [ t for t in self.frames if t > self.position ]
if not next:
return False
self.position = min(next)
return True
def prev_keyframe(self):
prevs = [ t for t in self.frames if t < self.position ]
if not prevs:
return False
self.position = max(prevs)
return True
def move_position(self, delta):
self.position = max(self.position+delta, 0)
return True
def move_start(self):
self.position = 0
return True
def move_end(self):
if self.frames:
self.position = max( self.frames )
else:
self.position = 0
return True
def insert_keyframe(self):
if self.position not in self.frames:
t, sk = self.get_keyframe(-1)
if not sk:
sk = self.skeleton
self.frames[ self.position ] = copy.deepcopy(sk)
return True
return False
def remove_keyframe(self):
if self.position in self.frames:
del self.frames[ self.position ]
return True
return False
def insert_time(self, delta):
new_frames = {}
for t, sk in sorted(self.frames.items()):
if t >= self.position:
t += delta
new_frames[ t ] = sk
self.frames = new_frames
def delete_time(self, delta):
for t in self.frames:
if self.position <= t < self.position + delta:
return False
new_frames = {}
for t, sk in sorted(self.frames.items()):
if t > self.position:
t -= delta
new_frames[ t ] = sk
self.frames = new_frames
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
class Path:
def at(self, t):
pass
class Bezier(Path):
def __init__(self, a, b, ac, bc):
self.a = a
self.b = b
self.ac = ac
self.bc = bc
def at(self, t):
def calc(i):
a = self.a[i]
b = self.ac[i]
c = self.bc[i]
d = self.b[i]
return (
((1-t)**3) * a +
3*t*((1-t)**2)*b +
3*(t**2)*(1-t)*c +
(t**3)*d
)
return calc(0), calc(1)
def __repr__(self):
return "Bezier( (%i,%i), (%i,%i), (%i, %i), (%i,%i) )"%(
self.a[0], self.a[0],
self.b[0], self.b[1],
self.ac[0], self.ac[1],
self.bc[0], self.bc[1],
)
| Python |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2010 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of cocos2d nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
Sprites allows to display a image in a rectangular area, which can be rotated,
scaled and moved.
The placement in the scene follows the standard CocosNode rules.
Also, all stock actions will work with sprites.
Animating a sprite
==================
Animation as in cartoon style animation, that is, replacing the image fast
enough to give the illusion of movement, can be accomplished by:
- using an animated .gif file as source for the image
- passing a pyglet.image.Animation as image, which collects a number of images
- have an array of images and let your code assign to the sprite image member
Changing a sprite by way of actions
===================================
To execute any action you need to create an action::
move = MoveBy( (50,0), 5 )
In this case, ``move`` is an action that will move the sprite
50 pixels to the right (``x`` coordinate) and 0 pixel in the ``y`` coordinate
in 5 seconds.
And now tell the sprite to execute it::
sprite.do( move )
'''
__docformat__ = 'restructuredtext'
import math
import pyglet
from pyglet import image
from pyglet.gl import *
import cocosnode
from batch import *
import rect
import euclid
import math
__all__ = [ 'Sprite', # Sprite class
]
class Sprite( BatchableNode, pyglet.sprite.Sprite):
'''A CocosNode that displays a rectangular image.
Example::
sprite = Sprite('grossini.png')
'''
def __init__( self, image, position=(0,0), rotation=0, scale=1, opacity = 255, color=(255,255,255), anchor = None ):
'''Initialize the sprite
:Parameters:
`image` : string or image
name of the image resource or a pyglet image.
`position` : tuple
position of the anchor. Defaults to (0,0)
`rotation` : float
the rotation (degrees). Defaults to 0.
`scale` : float
the zoom factor. Defaults to 1.
`opacity` : int
the opacity (0=transparent, 255=opaque). Defaults to 255.
`color` : tuple
the color to colorize the child (RGB 3-tuple). Defaults to (255,255,255).
`anchor` : (float, float)
(x,y)-point from where the image will be positions, rotated and scaled in pixels. For example (image.width/2, image.height/2) is the center (default).
'''
if isinstance(image, str):
image = pyglet.resource.image(image)
self.transform_anchor_x = 0
self.transform_anchor_y = 0
self._image_anchor_x = 0
self._image_anchor_y = 0
pyglet.sprite.Sprite.__init__(self, image)
BatchableNode.__init__(self)
if anchor is None:
if isinstance(self.image, pyglet.image.Animation):
anchor = (image.frames[0].image.width / 2,
image.frames[0].image.height / 2)
else:
anchor = image.width / 2, image.height / 2
self.image_anchor = anchor
# group.
# This is for batching
self.group = None
# children group.
# This is for batching
self.children_group = None
#: position of the sprite in (x,y) coordinates
self.position = position
#: rotation degrees of the sprite. Default: 0 degrees
self.rotation = rotation
#: scale of the sprite where 1.0 the default value
self.scale = scale
#: opacity of the sprite where 0 is transparent and 255 is solid
self.opacity = opacity
#: color of the sprite in R,G,B format where 0,0,0 is black and 255,255,255 is white
self.color = color
def get_rect(self):
'''Get a cocos.rect.Rect for this sprite.'''
x, y = self.position
x -= self.image_anchor_x
y -= self.image_anchor_y
return rect.Rect(x, y, self.width, self.height)
def get_AABB(self):
'''Returns a local-coordinates Axis aligned Bounding Box'''
v = self._vertex_list.vertices
x = v[0], v[2], v[4], v[6]
y = v[1], v[3], v[5], v[7]
return rect.Rect(min(x),min(y),max(x)-min(x),max(y)-min(y))
def _set_rotation( self, a ):
pyglet.sprite.Sprite._set_rotation(self, a)
BatchableNode._set_rotation(self,a)
def _set_scale( self, s ):
pyglet.sprite.Sprite._set_scale(self,s)
BatchableNode._set_scale(self,s)
def _set_position( self, p ):
pyglet.sprite.Sprite.position = p
BatchableNode._set_position(self,p)
def _set_x(self, x ):
pyglet.sprite.Sprite._set_x( self, x )
BatchableNode._set_x( self, x)
def _set_y(self, y ):
pyglet.sprite.Sprite._set_y( self, y )
BatchableNode._set_y( self, y)
def contains(self, x, y):
'''Test whether this (untransformed) Sprite contains the pixel coordinates
given.
'''
sx, sy = self.position
ax, ay = self.image_anchor
sx -= ax
sy -= ay
if x < sx or x > sx + self.width: return False
if y < sy or y > sy + self.height: return False
return True
def _set_anchor_x(self, value):
self._image_anchor_x = value
self._update_position()
def _get_anchor_x(self):
return self._image_anchor_x
image_anchor_x = property(_get_anchor_x, _set_anchor_x)
def _set_anchor_y(self, value):
self._image_anchor_y = value
self._update_position()
def _get_anchor_y(self):
return self._image_anchor_y
image_anchor_y = property(_get_anchor_y, _set_anchor_y)
def _set_anchor(self, value):
self._image_anchor_x = value[0]
self._image_anchor_y = value[1]
self._update_position()
def _get_anchor(self):
return (self._get_anchor_x(), self._get_anchor_y())
image_anchor = property(_get_anchor, _set_anchor)
def draw(self):
"""
When the sprite is not into a batch it will be draw with this method.
If in a batch, this method is not called, and the draw is done by
the batch.
"""
self._group.set_state()
if self._vertex_list is not None:
self._vertex_list.draw(GL_QUADS)
self._group.unset_state()
def _update_position(self):
"""updates vertex list"""
if not self._visible:
self._vertex_list.vertices[:] = [0, 0, 0, 0, 0, 0, 0, 0]
return
img = self._texture
if self.transform_anchor_x == self.transform_anchor_y == 0:
if self._rotation:
x1 = -self._image_anchor_x * self._scale
y1 = -self._image_anchor_y * self._scale
x2 = x1 + img.width * self._scale
y2 = y1 + img.height * self._scale
x = self._x
y = self._y
r = -math.radians(self._rotation)
cr = math.cos(r)
sr = math.sin(r)
ax = int(x1 * cr - y1 * sr + x)
ay = int(x1 * sr + y1 * cr + y)
bx = int(x2 * cr - y1 * sr + x)
by = int(x2 * sr + y1 * cr + y)
cx = int(x2 * cr - y2 * sr + x)
cy = int(x2 * sr + y2 * cr + y)
dx = int(x1 * cr - y2 * sr + x)
dy = int(x1 * sr + y2 * cr + y)
self._vertex_list.vertices[:] = [ax, ay, bx, by, cx, cy, dx, dy]
elif self._scale != 1.0:
x1 = int(self._x - self._image_anchor_x * self._scale)
y1 = int(self._y - self._image_anchor_y * self._scale)
x2 = int(x1 + img.width * self._scale)
y2 = int(y1 + img.height * self._scale)
self._vertex_list.vertices[:] = [x1, y1, x2, y1, x2, y2, x1, y2]
else:
x1 = int(self._x - self._image_anchor_x)
y1 = int(self._y - self._image_anchor_y)
x2 = x1 + img.width
y2 = y1 + img.height
self._vertex_list.vertices[:] = [x1, y1, x2, y1, x2, y2, x1, y2]
else:
x1 = int(- self._image_anchor_x)
y1 = int(- self._image_anchor_y)
x2 = x1 + img.width
y2 = y1 + img.height
m = self.get_local_transform()
p1 = m * euclid.Point2(x1, y1)
p2 = m * euclid.Point2(x2, y1)
p3 = m * euclid.Point2(x2, y2)
p4 = m * euclid.Point2(x1, y2)
self._vertex_list.vertices[:] = [
int(p1.x), int(p1.y), int(p2.x), int(p2.y),
int(p3.x), int(p3.y), int(p4.x), int(p4.y)]
Sprite.supported_classes = Sprite
| Python |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: xlib.py 2496 2009-08-19 01:17:30Z benjamin.coder.smith $'
import select
from pyglet.app import displays, windows, BaseEventLoop
from pyglet.window.xlib import xlib
class XlibEventLoop(BaseEventLoop):
def run(self):
self._setup()
e = xlib.XEvent()
t = 0
sleep_time = 0.
self.dispatch_event('on_enter')
while not self.has_exit:
# Check for already pending events
for display in displays:
if xlib.XPending(display._display):
pending_displays = (display,)
break
else:
# None found; select on all file descriptors or timeout
iwtd = self.get_select_files()
pending_displays, _, _ = select.select(iwtd, (), (), sleep_time)
# Dispatch platform events
for display in pending_displays:
while xlib.XPending(display._display):
xlib.XNextEvent(display._display, e)
# Key events are filtered by the xlib window event
# handler so they get a shot at the prefiltered event.
if e.xany.type not in (xlib.KeyPress, xlib.KeyRelease):
if xlib.XFilterEvent(e, e.xany.window):
continue
try:
window = display._window_map[e.xany.window]
except KeyError:
continue
window.dispatch_platform_event(e)
# Dispatch resize events
for window in windows:
if window._needs_resize:
window.switch_to()
window.dispatch_event('on_resize',
window._width, window._height)
window.dispatch_event('on_expose')
window._needs_resize = False
sleep_time = self.idle()
self.dispatch_event('on_exit')
def get_select_files(self):
return list(displays)
| Python |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
# $Id:$
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import ctypes
import time
from pyglet.app import windows, BaseEventLoop
from pyglet.window.win32 import _user32, types, constants
class Win32EventLoop(BaseEventLoop):
def run(self):
self._setup()
self._timer_proc = types.TIMERPROC(self._timer_func)
self._timer = timer = _user32.SetTimer(0, 0, 0, self._timer_proc)
self._polling = False
self._allow_polling = True
msg = types.MSG()
self.dispatch_event('on_enter')
while not self.has_exit:
if self._polling:
while _user32.PeekMessageW(ctypes.byref(msg),
0, 0, 0, constants.PM_REMOVE):
_user32.TranslateMessage(ctypes.byref(msg))
_user32.DispatchMessageW(ctypes.byref(msg))
self._timer_func(0, 0, timer, 0)
else:
_user32.GetMessageW(ctypes.byref(msg), 0, 0, 0)
_user32.TranslateMessage(ctypes.byref(msg))
_user32.DispatchMessageW(ctypes.byref(msg))
# Manual idle event
msg_types = \
_user32.GetQueueStatus(constants.QS_ALLINPUT) & 0xffff0000
if (msg.message != constants.WM_TIMER and
not msg_types & ~(constants.QS_TIMER<<16)):
self._timer_func(0, 0, timer, 0)
self.dispatch_event('on_exit')
def _idle_chance(self):
if (self._next_idle_time is not None and
self._next_idle_time <= time.time()):
self._timer_func(0, 0, self._timer, 0)
def _timer_func(self, hwnd, msg, timer, t):
sleep_time = self.idle()
if sleep_time is None:
# Block indefinitely
millis = constants.USER_TIMER_MAXIMUM
self._next_idle_time = None
self._polling = False
_user32.SetTimer(0, timer, millis, self._timer_proc)
elif sleep_time < 0.01 and self._allow_polling:
# Degenerate to polling
millis = constants.USER_TIMER_MAXIMUM
self._next_idle_time = 0.
if not self._polling:
self._polling = True
_user32.SetTimer(0, timer, millis, self._timer_proc)
else:
# Block until timer
# XXX hack to avoid oversleep; needs to be api
sleep_time = max(sleep_time - 0.01, 0)
millis = int(sleep_time * 1000)
self._next_idle_time = time.time() + sleep_time
self._polling = False
_user32.SetTimer(0, timer, millis, self._timer_proc)
| Python |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Application-wide functionality.
Most applications need only call `run` after creating one or more windows
to begin processing events. For example, a simple application consisting of
one window is::
from pyglet import app
from pyglet import window
win = window.Window()
app.run()
To handle events on the main event loop, instantiate it manually. The
following example exits the application as soon as any window is closed (the
default policy is to wait until all windows are closed)::
event_loop = app.EventLoop()
@event_loop.event
def on_window_close(window):
event_loop.exit()
:since: pyglet 1.1
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: __init__.py 2140 2008-07-27 04:15:52Z Alex.Holkner $'
import sys
import weakref
from pyglet import clock
from pyglet import event
_is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc
class WeakSet(object):
'''Set of objects, referenced weakly.
Adding an object to this set does not prevent it from being garbage
collected. Upon being garbage collected, the object is automatically
removed from the set.
'''
def __init__(self):
self._dict = weakref.WeakKeyDictionary()
def add(self, value):
self._dict[value] = True
def remove(self, value):
del self._dict[value]
def __iter__(self):
for key in self._dict.keys():
yield key
def __contains__(self, other):
return other in self._dict
def __len__(self):
return len(self._dict)
#: Set of all open displays. Instances of `Display` are automatically added
#: to this set upon construction. The set uses weak references, so displays
#: are removed from the set when they are no longer referenced.
#:
#: :type: `WeakSet`
displays = WeakSet()
#: Set of all open windows (including invisible windows). Instances of
#: `Window` are automatically added to this set upon construction. The set
#: uses weak references, so windows are removed from the set when they are no
#: longer referenced or are closed explicitly.
#:
#: :type: `WeakSet`
windows = WeakSet()
class BaseEventLoop(event.EventDispatcher):
'''The main run loop of the application.
Calling `run` begins the application event loop, which processes
operating system events, calls `pyglet.clock.tick` to call scheduled
functions and calls `pyglet.window.Window.on_draw` and
`pyglet.window.Window.flip` to update window contents.
Applications can subclass `EventLoop` and override certain methods
to integrate another framework's run loop, or to customise processing
in some other way. You should not in general override `run`, as
this method contains platform-specific code that ensures the application
remains responsive to the user while keeping CPU usage to a minimum.
'''
#: Flag indicating if the event loop will exit in the next iteration.
#: This is
has_exit = False
def run(self):
'''Begin processing events, scheduled functions and window updates.
This method returns when `has_exit` is set to True.
Developers are discouraged from overriding this method, as the
implementation is platform-specific.
'''
raise NotImplementedError('abstract')
def _setup(self):
global event_loop
event_loop = self
# Disable event queuing for dispatch_events
from pyglet.window import Window
Window._enable_event_queue = False
# Dispatch pending events
for window in windows:
window.switch_to()
window.dispatch_pending_events()
def _idle_chance(self):
'''If timeout has expired, manually force an idle loop.
Called by window that have blocked the event loop (e.g. during
resizing).
'''
def idle(self):
'''Called during each iteration of the event loop.
The method is called immediately after any window events (i.e., after
any user input). The method can return a duration after which
the idle method will be called again. The method may be called
earlier if the user creates more input events. The method
can return `None` to only wait for user events.
For example, return ``1.0`` to have the idle method called every
second, or immediately after any user events.
The default implementation dispatches the
`pyglet.window.Window.on_draw` event for all windows and uses
`pyglet.clock.tick` and `pyglet.clock.get_sleep_time` on the default
clock to determine the return value.
This method should be overridden by advanced users only. To have
code execute at regular intervals, use the
`pyglet.clock.schedule` methods.
:rtype: float
:return: The number of seconds before the idle method should
be called again, or `None` to block for user input.
'''
dt = clock.tick(True)
# Redraw all windows
for window in windows:
if window.invalid:
window.switch_to()
window.dispatch_event('on_draw')
window.flip()
# Update timout
return clock.get_sleep_time(True)
def exit(self):
'''Safely exit the event loop at the end of the current iteration.
This method is convenience for setting `has_exit` to ``True``.
'''
self.has_exit = True
def on_window_close(self, window):
'''Default window close handler.'''
if not windows:
self.exit()
if _is_epydoc:
def on_window_close(window):
'''A window was closed.
This event is dispatched when a window is closed. It is not
dispatched if the window's close button was pressed but the
window did not close.
The default handler calls `exit` if no more windows are open. You
can override this handler to base your application exit on some
other policy.
:event:
'''
def on_enter():
'''The event loop is about to begin.
This is dispatched when the event loop is prepared to enter
the main run loop, and represents the last chance for an
application to initialise itself.
:event:
'''
def on_exit():
'''The event loop is about to exit.
After dispatching this event, the `run` method returns (the
application may not actually exit if you have more code
following the `run` invocation).
:event:
'''
BaseEventLoop.register_event_type('on_window_close')
BaseEventLoop.register_event_type('on_enter')
BaseEventLoop.register_event_type('on_exit')
#: The global event loop. Set to the correct instance when an `EventLoop` is
#: started.
#:
#: :type: `EventLoop`
event_loop = None
def run():
'''Begin processing events, scheduled functions and window updates.
This is a convenience function, equivalent to::
EventLoop().run()
'''
EventLoop().run()
def exit():
'''Exit the application event loop.
Causes the application event loop to finish, if an event loop is currently
running. The application may not necessarily exit (for example, there may
be additional code following the `run` invocation).
This is a convenience function, equivalent to::
event_loop.exit()
'''
if event_loop:
event_loop.exit()
if _is_epydoc:
EventLoop = BaseEventLoop
EventLoop.__name__ = 'EventLoop'
del BaseEventLoop
else:
# Permit cyclic import.
import pyglet
pyglet.app = sys.modules[__name__]
if sys.platform == 'darwin':
from pyglet.app.carbon import CarbonEventLoop as EventLoop
elif sys.platform in ('win32', 'cygwin'):
from pyglet.app.win32 import Win32EventLoop as EventLoop
else:
from pyglet.app.xlib import XlibEventLoop as EventLoop
| Python |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import ctypes
from pyglet.app import windows, BaseEventLoop
from pyglet.window.carbon import carbon, types, constants, _oscheck
EventLoopTimerProc = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p)
kEventDurationForever = ctypes.c_double(constants.kEventDurationForever)
class CarbonEventLoop(BaseEventLoop):
def run(self):
self._setup()
e = ctypes.c_void_p()
event_dispatcher = carbon.GetEventDispatcherTarget()
self._event_loop = event_loop = carbon.GetMainEventLoop()
event_queue = carbon.GetMainEventQueue()
self._timer = timer = ctypes.c_void_p()
idle_event_proc = EventLoopTimerProc(self._timer_proc)
carbon.InstallEventLoopTimer(event_loop,
ctypes.c_double(0.1), #?
kEventDurationForever,
idle_event_proc,
None,
ctypes.byref(timer))
self._force_idle = False
self._allow_polling = True
self.dispatch_event('on_enter')
while not self.has_exit:
if self._force_idle:
duration = 0
else:
duration = kEventDurationForever
if carbon.ReceiveNextEvent(0, None, duration,
True, ctypes.byref(e)) == 0:
carbon.SendEventToEventTarget(e, event_dispatcher)
carbon.ReleaseEvent(e)
# Manual idle event
if carbon.GetNumEventsInQueue(event_queue) == 0 or self._force_idle:
self._force_idle = False
self._timer_proc(timer, None, False)
carbon.RemoveEventLoopTimer(self._timer)
self.dispatch_event('on_exit')
def _stop_polling(self):
carbon.SetEventLoopTimerNextFireTime(self._timer, ctypes.c_double(0.0))
def _enter_blocking(self):
carbon.SetEventLoopTimerNextFireTime(self._timer, ctypes.c_double(0.0))
self._allow_polling = False
def _exit_blocking(self):
self._allow_polling = True
def _timer_proc(self, timer, data, in_events=True):
allow_polling = True
for window in windows:
# Check for live resizing
if window._resizing is not None:
allow_polling = False
old_width, old_height = window._resizing
rect = types.Rect()
carbon.GetWindowBounds(window._window,
constants.kWindowContentRgn,
ctypes.byref(rect))
width = rect.right - rect.left
height = rect.bottom - rect.top
if width != old_width or height != old_height:
window._resizing = width, height
window.switch_to()
window.dispatch_event('on_resize', width, height)
# Check for live dragging
if window._dragging:
allow_polling = False
# Check for deferred recreate
if window._recreate_deferred:
if in_events:
# Break out of ReceiveNextEvent so it can be processed
# in next iteration.
carbon.QuitEventLoop(self._event_loop)
self._force_idle = True
else:
# Do it now.
window._recreate_immediate()
sleep_time = self.idle()
if sleep_time is None:
sleep_time = constants.kEventDurationForever
elif sleep_time < 0.01 and allow_polling and self._allow_polling:
# Switch event loop to polling.
if in_events:
carbon.QuitEventLoop(self._event_loop)
self._force_idle = True
sleep_time = constants.kEventDurationForever
carbon.SetEventLoopTimerNextFireTime(timer, ctypes.c_double(sleep_time))
| Python |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Information about version and extensions of current GLX implementation.
Usage::
from pyglet.gl import glx_info
if glx_info.have_extension('GLX_NV_float_buffer'):
# ...
Or, if using more than one display::
from pyglet.gl.glx_info import GLXInfo
info = GLXInfo(window._display)
if info.get_server_vendor() == 'ATI':
# ...
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: glx_info.py 1579 2008-01-15 14:47:19Z Alex.Holkner $'
from ctypes import *
from pyglet.gl.glx import *
from pyglet.gl.glx import Display
class GLXInfoException(Exception):
pass
class GLXInfo(object):
def __init__(self, display=None):
self.display = display
def set_display(self, display):
self.display = cast(pointer(display), POINTER(Display))
def check_display(self):
if not self.display:
raise GLXInfoException('No X11 display has been set yet.')
def have_version(self, major, minor=0):
self.check_display()
if not glXQueryExtension(self.display, None, None):
raise GLXInfoException('pyglet requires an X server with GLX')
server_version = self.get_server_version().split()[0]
client_version = self.get_client_version().split()[0]
server = [int(i) for i in server_version.split('.')]
client = [int(i) for i in client_version.split('.')]
return (tuple(server) >= (major, minor) and
tuple(client) >= (major, minor))
def get_server_vendor(self):
self.check_display()
return glXQueryServerString(self.display, 0, GLX_VENDOR)
def get_server_version(self):
# glXQueryServerString was introduced in GLX 1.1, so we need to use the
# 1.0 function here which queries the server implementation for its
# version.
self.check_display()
major = c_int()
minor = c_int()
if not glXQueryVersion(self.display, byref(major), byref(minor)):
raise GLXInfoException('Could not determine GLX server version')
return '%s.%s'%(major.value, minor.value)
def get_server_extensions(self):
self.check_display()
return glXQueryServerString(self.display, 0, GLX_EXTENSIONS).split()
def get_client_vendor(self):
self.check_display()
return glXGetClientString(self.display, GLX_VENDOR)
def get_client_version(self):
self.check_display()
return glXGetClientString(self.display, GLX_VERSION)
def get_client_extensions(self):
self.check_display()
return glXGetClientString(self.display, GLX_EXTENSIONS).split()
def get_extensions(self):
self.check_display()
return glXQueryExtensionsString(self.display, 0).split()
def have_extension(self, extension):
self.check_display()
if not self.have_version(1, 1):
return False
return extension in self.get_extensions()
# Single instance suitable for apps that use only a single display.
_glx_info = GLXInfo()
set_display = _glx_info.set_display
check_display = _glx_info.check_display
have_version = _glx_info.have_version
get_server_vendor = _glx_info.get_server_vendor
get_server_version = _glx_info.get_server_version
get_server_extensions = _glx_info.get_server_extensions
get_client_vendor = _glx_info.get_client_vendor
get_client_version = _glx_info.get_client_version
get_client_extensions = _glx_info.get_client_extensions
get_extensions = _glx_info.get_extensions
have_extension = _glx_info.have_extension
| Python |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: lib_glx.py 597 2007-02-03 16:13:07Z Alex.Holkner $'
import ctypes
from ctypes import *
import pyglet
from pyglet.gl.lib import missing_function, decorate_function
__all__ = ['link_GL', 'link_GLU', 'link_WGL']
_debug_trace = pyglet.options['debug_trace']
gl_lib = ctypes.windll.opengl32
glu_lib = ctypes.windll.glu32
wgl_lib = gl_lib
if _debug_trace:
from pyglet.lib import _TraceLibrary
gl_lib = _TraceLibrary(gl_lib)
glu_lib = _TraceLibrary(glu_lib)
wgl_lib = _TraceLibrary(wgl_lib)
try:
wglGetProcAddress = wgl_lib.wglGetProcAddress
wglGetProcAddress.restype = CFUNCTYPE(POINTER(c_int))
wglGetProcAddress.argtypes = [c_char_p]
_have_get_proc_address = True
except AttributeError:
_have_get_proc_address = False
class WGLFunctionProxy(object):
__slots__ = ['name', 'requires', 'suggestions', 'ftype', 'func']
def __init__(self, name, ftype, requires, suggestions):
assert _have_get_proc_address
self.name = name
self.ftype = ftype
self.requires = requires
self.suggestions = suggestions
self.func = None
def __call__(self, *args, **kwargs):
if self.func:
return self.func(*args, **kwargs)
from pyglet.gl import current_context
if not current_context:
raise Exception(
'Call to function "%s" before GL context created' % self.name)
address = wglGetProcAddress(self.name)
if cast(address, POINTER(c_int)): # check cast because address is func
self.func = cast(address, self.ftype)
decorate_function(self.func, self.name)
else:
self.func = missing_function(
self.name, self.requires, self.suggestions)
result = self.func(*args, **kwargs)
return result
def link_GL(name, restype, argtypes, requires=None, suggestions=None):
try:
func = getattr(gl_lib, name)
func.restype = restype
func.argtypes = argtypes
decorate_function(func, name)
return func
except AttributeError, e:
# Not in opengl32.dll. Try and get a pointer from WGL.
try:
fargs = (restype,) + tuple(argtypes)
ftype = ctypes.WINFUNCTYPE(*fargs)
if _have_get_proc_address:
from pyglet.gl import gl_info
if gl_info.have_context():
address = wglGetProcAddress(name)
if address:
func = cast(address, ftype)
decorate_function(func, name)
return func
else:
# Insert proxy until we have a context
return WGLFunctionProxy(name, ftype, requires, suggestions)
except:
pass
return missing_function(name, requires, suggestions)
def link_GLU(name, restype, argtypes, requires=None, suggestions=None):
try:
func = getattr(glu_lib, name)
func.restype = restype
func.argtypes = argtypes
decorate_function(func, name)
return func
except AttributeError, e:
# Not in glu32.dll. Try and get a pointer from WGL.
try:
fargs = (restype,) + tuple(argtypes)
ftype = ctypes.WINFUNCTYPE(*fargs)
if _have_get_proc_address:
from pyglet.gl import gl_info
if gl_info.have_context():
address = wglGetProcAddress(name)
if address:
func = cast(address, ftype)
decorate_function(func, name)
return func
else:
# Insert proxy until we have a context
return WGLFunctionProxy(name, ftype, requires, suggestions)
except:
pass
return missing_function(name, requires, suggestions)
link_WGL = link_GL
| Python |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Wrapper for /usr/include/GL/glu.h
Generated by tools/gengl.py.
Do not modify this file.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: glu.py 1579 2008-01-15 14:47:19Z Alex.Holkner $'
from ctypes import *
from pyglet.gl.lib import link_GLU as _link_function
from pyglet.gl.lib import c_ptrdiff_t
# BEGIN GENERATED CONTENT (do not edit below this line)
# This content is generated by tools/gengl.py.
# Wrapper for /usr/include/GL/glu.h
GLU_EXT_object_space_tess = 1 # /usr/include/GL/glu.h:58
GLU_EXT_nurbs_tessellator = 1 # /usr/include/GL/glu.h:59
GLU_FALSE = 0 # /usr/include/GL/glu.h:62
GLU_TRUE = 1 # /usr/include/GL/glu.h:63
GLU_VERSION_1_1 = 1 # /usr/include/GL/glu.h:66
GLU_VERSION_1_2 = 1 # /usr/include/GL/glu.h:67
GLU_VERSION_1_3 = 1 # /usr/include/GL/glu.h:68
GLU_VERSION = 100800 # /usr/include/GL/glu.h:71
GLU_EXTENSIONS = 100801 # /usr/include/GL/glu.h:72
GLU_INVALID_ENUM = 100900 # /usr/include/GL/glu.h:75
GLU_INVALID_VALUE = 100901 # /usr/include/GL/glu.h:76
GLU_OUT_OF_MEMORY = 100902 # /usr/include/GL/glu.h:77
GLU_INCOMPATIBLE_GL_VERSION = 100903 # /usr/include/GL/glu.h:78
GLU_INVALID_OPERATION = 100904 # /usr/include/GL/glu.h:79
GLU_OUTLINE_POLYGON = 100240 # /usr/include/GL/glu.h:83
GLU_OUTLINE_PATCH = 100241 # /usr/include/GL/glu.h:84
GLU_NURBS_ERROR = 100103 # /usr/include/GL/glu.h:87
GLU_ERROR = 100103 # /usr/include/GL/glu.h:88
GLU_NURBS_BEGIN = 100164 # /usr/include/GL/glu.h:89
GLU_NURBS_BEGIN_EXT = 100164 # /usr/include/GL/glu.h:90
GLU_NURBS_VERTEX = 100165 # /usr/include/GL/glu.h:91
GLU_NURBS_VERTEX_EXT = 100165 # /usr/include/GL/glu.h:92
GLU_NURBS_NORMAL = 100166 # /usr/include/GL/glu.h:93
GLU_NURBS_NORMAL_EXT = 100166 # /usr/include/GL/glu.h:94
GLU_NURBS_COLOR = 100167 # /usr/include/GL/glu.h:95
GLU_NURBS_COLOR_EXT = 100167 # /usr/include/GL/glu.h:96
GLU_NURBS_TEXTURE_COORD = 100168 # /usr/include/GL/glu.h:97
GLU_NURBS_TEX_COORD_EXT = 100168 # /usr/include/GL/glu.h:98
GLU_NURBS_END = 100169 # /usr/include/GL/glu.h:99
GLU_NURBS_END_EXT = 100169 # /usr/include/GL/glu.h:100
GLU_NURBS_BEGIN_DATA = 100170 # /usr/include/GL/glu.h:101
GLU_NURBS_BEGIN_DATA_EXT = 100170 # /usr/include/GL/glu.h:102
GLU_NURBS_VERTEX_DATA = 100171 # /usr/include/GL/glu.h:103
GLU_NURBS_VERTEX_DATA_EXT = 100171 # /usr/include/GL/glu.h:104
GLU_NURBS_NORMAL_DATA = 100172 # /usr/include/GL/glu.h:105
GLU_NURBS_NORMAL_DATA_EXT = 100172 # /usr/include/GL/glu.h:106
GLU_NURBS_COLOR_DATA = 100173 # /usr/include/GL/glu.h:107
GLU_NURBS_COLOR_DATA_EXT = 100173 # /usr/include/GL/glu.h:108
GLU_NURBS_TEXTURE_COORD_DATA = 100174 # /usr/include/GL/glu.h:109
GLU_NURBS_TEX_COORD_DATA_EXT = 100174 # /usr/include/GL/glu.h:110
GLU_NURBS_END_DATA = 100175 # /usr/include/GL/glu.h:111
GLU_NURBS_END_DATA_EXT = 100175 # /usr/include/GL/glu.h:112
GLU_NURBS_ERROR1 = 100251 # /usr/include/GL/glu.h:115
GLU_NURBS_ERROR2 = 100252 # /usr/include/GL/glu.h:116
GLU_NURBS_ERROR3 = 100253 # /usr/include/GL/glu.h:117
GLU_NURBS_ERROR4 = 100254 # /usr/include/GL/glu.h:118
GLU_NURBS_ERROR5 = 100255 # /usr/include/GL/glu.h:119
GLU_NURBS_ERROR6 = 100256 # /usr/include/GL/glu.h:120
GLU_NURBS_ERROR7 = 100257 # /usr/include/GL/glu.h:121
GLU_NURBS_ERROR8 = 100258 # /usr/include/GL/glu.h:122
GLU_NURBS_ERROR9 = 100259 # /usr/include/GL/glu.h:123
GLU_NURBS_ERROR10 = 100260 # /usr/include/GL/glu.h:124
GLU_NURBS_ERROR11 = 100261 # /usr/include/GL/glu.h:125
GLU_NURBS_ERROR12 = 100262 # /usr/include/GL/glu.h:126
GLU_NURBS_ERROR13 = 100263 # /usr/include/GL/glu.h:127
GLU_NURBS_ERROR14 = 100264 # /usr/include/GL/glu.h:128
GLU_NURBS_ERROR15 = 100265 # /usr/include/GL/glu.h:129
GLU_NURBS_ERROR16 = 100266 # /usr/include/GL/glu.h:130
GLU_NURBS_ERROR17 = 100267 # /usr/include/GL/glu.h:131
GLU_NURBS_ERROR18 = 100268 # /usr/include/GL/glu.h:132
GLU_NURBS_ERROR19 = 100269 # /usr/include/GL/glu.h:133
GLU_NURBS_ERROR20 = 100270 # /usr/include/GL/glu.h:134
GLU_NURBS_ERROR21 = 100271 # /usr/include/GL/glu.h:135
GLU_NURBS_ERROR22 = 100272 # /usr/include/GL/glu.h:136
GLU_NURBS_ERROR23 = 100273 # /usr/include/GL/glu.h:137
GLU_NURBS_ERROR24 = 100274 # /usr/include/GL/glu.h:138
GLU_NURBS_ERROR25 = 100275 # /usr/include/GL/glu.h:139
GLU_NURBS_ERROR26 = 100276 # /usr/include/GL/glu.h:140
GLU_NURBS_ERROR27 = 100277 # /usr/include/GL/glu.h:141
GLU_NURBS_ERROR28 = 100278 # /usr/include/GL/glu.h:142
GLU_NURBS_ERROR29 = 100279 # /usr/include/GL/glu.h:143
GLU_NURBS_ERROR30 = 100280 # /usr/include/GL/glu.h:144
GLU_NURBS_ERROR31 = 100281 # /usr/include/GL/glu.h:145
GLU_NURBS_ERROR32 = 100282 # /usr/include/GL/glu.h:146
GLU_NURBS_ERROR33 = 100283 # /usr/include/GL/glu.h:147
GLU_NURBS_ERROR34 = 100284 # /usr/include/GL/glu.h:148
GLU_NURBS_ERROR35 = 100285 # /usr/include/GL/glu.h:149
GLU_NURBS_ERROR36 = 100286 # /usr/include/GL/glu.h:150
GLU_NURBS_ERROR37 = 100287 # /usr/include/GL/glu.h:151
GLU_AUTO_LOAD_MATRIX = 100200 # /usr/include/GL/glu.h:154
GLU_CULLING = 100201 # /usr/include/GL/glu.h:155
GLU_SAMPLING_TOLERANCE = 100203 # /usr/include/GL/glu.h:156
GLU_DISPLAY_MODE = 100204 # /usr/include/GL/glu.h:157
GLU_PARAMETRIC_TOLERANCE = 100202 # /usr/include/GL/glu.h:158
GLU_SAMPLING_METHOD = 100205 # /usr/include/GL/glu.h:159
GLU_U_STEP = 100206 # /usr/include/GL/glu.h:160
GLU_V_STEP = 100207 # /usr/include/GL/glu.h:161
GLU_NURBS_MODE = 100160 # /usr/include/GL/glu.h:162
GLU_NURBS_MODE_EXT = 100160 # /usr/include/GL/glu.h:163
GLU_NURBS_TESSELLATOR = 100161 # /usr/include/GL/glu.h:164
GLU_NURBS_TESSELLATOR_EXT = 100161 # /usr/include/GL/glu.h:165
GLU_NURBS_RENDERER = 100162 # /usr/include/GL/glu.h:166
GLU_NURBS_RENDERER_EXT = 100162 # /usr/include/GL/glu.h:167
GLU_OBJECT_PARAMETRIC_ERROR = 100208 # /usr/include/GL/glu.h:170
GLU_OBJECT_PARAMETRIC_ERROR_EXT = 100208 # /usr/include/GL/glu.h:171
GLU_OBJECT_PATH_LENGTH = 100209 # /usr/include/GL/glu.h:172
GLU_OBJECT_PATH_LENGTH_EXT = 100209 # /usr/include/GL/glu.h:173
GLU_PATH_LENGTH = 100215 # /usr/include/GL/glu.h:174
GLU_PARAMETRIC_ERROR = 100216 # /usr/include/GL/glu.h:175
GLU_DOMAIN_DISTANCE = 100217 # /usr/include/GL/glu.h:176
GLU_MAP1_TRIM_2 = 100210 # /usr/include/GL/glu.h:179
GLU_MAP1_TRIM_3 = 100211 # /usr/include/GL/glu.h:180
GLU_POINT = 100010 # /usr/include/GL/glu.h:183
GLU_LINE = 100011 # /usr/include/GL/glu.h:184
GLU_FILL = 100012 # /usr/include/GL/glu.h:185
GLU_SILHOUETTE = 100013 # /usr/include/GL/glu.h:186
GLU_SMOOTH = 100000 # /usr/include/GL/glu.h:192
GLU_FLAT = 100001 # /usr/include/GL/glu.h:193
GLU_NONE = 100002 # /usr/include/GL/glu.h:194
GLU_OUTSIDE = 100020 # /usr/include/GL/glu.h:197
GLU_INSIDE = 100021 # /usr/include/GL/glu.h:198
GLU_TESS_BEGIN = 100100 # /usr/include/GL/glu.h:201
GLU_BEGIN = 100100 # /usr/include/GL/glu.h:202
GLU_TESS_VERTEX = 100101 # /usr/include/GL/glu.h:203
GLU_VERTEX = 100101 # /usr/include/GL/glu.h:204
GLU_TESS_END = 100102 # /usr/include/GL/glu.h:205
GLU_END = 100102 # /usr/include/GL/glu.h:206
GLU_TESS_ERROR = 100103 # /usr/include/GL/glu.h:207
GLU_TESS_EDGE_FLAG = 100104 # /usr/include/GL/glu.h:208
GLU_EDGE_FLAG = 100104 # /usr/include/GL/glu.h:209
GLU_TESS_COMBINE = 100105 # /usr/include/GL/glu.h:210
GLU_TESS_BEGIN_DATA = 100106 # /usr/include/GL/glu.h:211
GLU_TESS_VERTEX_DATA = 100107 # /usr/include/GL/glu.h:212
GLU_TESS_END_DATA = 100108 # /usr/include/GL/glu.h:213
GLU_TESS_ERROR_DATA = 100109 # /usr/include/GL/glu.h:214
GLU_TESS_EDGE_FLAG_DATA = 100110 # /usr/include/GL/glu.h:215
GLU_TESS_COMBINE_DATA = 100111 # /usr/include/GL/glu.h:216
GLU_CW = 100120 # /usr/include/GL/glu.h:219
GLU_CCW = 100121 # /usr/include/GL/glu.h:220
GLU_INTERIOR = 100122 # /usr/include/GL/glu.h:221
GLU_EXTERIOR = 100123 # /usr/include/GL/glu.h:222
GLU_UNKNOWN = 100124 # /usr/include/GL/glu.h:223
GLU_TESS_WINDING_RULE = 100140 # /usr/include/GL/glu.h:226
GLU_TESS_BOUNDARY_ONLY = 100141 # /usr/include/GL/glu.h:227
GLU_TESS_TOLERANCE = 100142 # /usr/include/GL/glu.h:228
GLU_TESS_ERROR1 = 100151 # /usr/include/GL/glu.h:231
GLU_TESS_ERROR2 = 100152 # /usr/include/GL/glu.h:232
GLU_TESS_ERROR3 = 100153 # /usr/include/GL/glu.h:233
GLU_TESS_ERROR4 = 100154 # /usr/include/GL/glu.h:234
GLU_TESS_ERROR5 = 100155 # /usr/include/GL/glu.h:235
GLU_TESS_ERROR6 = 100156 # /usr/include/GL/glu.h:236
GLU_TESS_ERROR7 = 100157 # /usr/include/GL/glu.h:237
GLU_TESS_ERROR8 = 100158 # /usr/include/GL/glu.h:238
GLU_TESS_MISSING_BEGIN_POLYGON = 100151 # /usr/include/GL/glu.h:239
GLU_TESS_MISSING_BEGIN_CONTOUR = 100152 # /usr/include/GL/glu.h:240
GLU_TESS_MISSING_END_POLYGON = 100153 # /usr/include/GL/glu.h:241
GLU_TESS_MISSING_END_CONTOUR = 100154 # /usr/include/GL/glu.h:242
GLU_TESS_COORD_TOO_LARGE = 100155 # /usr/include/GL/glu.h:243
GLU_TESS_NEED_COMBINE_CALLBACK = 100156 # /usr/include/GL/glu.h:244
GLU_TESS_WINDING_ODD = 100130 # /usr/include/GL/glu.h:247
GLU_TESS_WINDING_NONZERO = 100131 # /usr/include/GL/glu.h:248
GLU_TESS_WINDING_POSITIVE = 100132 # /usr/include/GL/glu.h:249
GLU_TESS_WINDING_NEGATIVE = 100133 # /usr/include/GL/glu.h:250
GLU_TESS_WINDING_ABS_GEQ_TWO = 100134 # /usr/include/GL/glu.h:251
class struct_GLUnurbs(Structure):
__slots__ = [
]
struct_GLUnurbs._fields_ = [
('_opaque_struct', c_int)
]
GLUnurbs = struct_GLUnurbs # /usr/include/GL/glu.h:261
class struct_GLUquadric(Structure):
__slots__ = [
]
struct_GLUquadric._fields_ = [
('_opaque_struct', c_int)
]
GLUquadric = struct_GLUquadric # /usr/include/GL/glu.h:262
class struct_GLUtesselator(Structure):
__slots__ = [
]
struct_GLUtesselator._fields_ = [
('_opaque_struct', c_int)
]
GLUtesselator = struct_GLUtesselator # /usr/include/GL/glu.h:263
GLUnurbsObj = GLUnurbs # /usr/include/GL/glu.h:266
GLUquadricObj = GLUquadric # /usr/include/GL/glu.h:267
GLUtesselatorObj = GLUtesselator # /usr/include/GL/glu.h:268
GLUtriangulatorObj = GLUtesselator # /usr/include/GL/glu.h:269
GLU_TESS_MAX_COORD = 9.9999999999999998e+149 # /usr/include/GL/glu.h:271
_GLUfuncptr = CFUNCTYPE(None) # /usr/include/GL/glu.h:274
# /usr/include/GL/glu.h:276
gluBeginCurve = _link_function('gluBeginCurve', None, [POINTER(GLUnurbs)], None)
# /usr/include/GL/glu.h:277
gluBeginPolygon = _link_function('gluBeginPolygon', None, [POINTER(GLUtesselator)], None)
# /usr/include/GL/glu.h:278
gluBeginSurface = _link_function('gluBeginSurface', None, [POINTER(GLUnurbs)], None)
# /usr/include/GL/glu.h:279
gluBeginTrim = _link_function('gluBeginTrim', None, [POINTER(GLUnurbs)], None)
GLint = c_int # /usr/include/GL/gl.h:58
GLenum = c_uint # /usr/include/GL/gl.h:53
GLsizei = c_int # /usr/include/GL/gl.h:59
# /usr/include/GL/glu.h:280
gluBuild1DMipmapLevels = _link_function('gluBuild1DMipmapLevels', GLint, [GLenum, GLint, GLsizei, GLenum, GLenum, GLint, GLint, GLint, POINTER(None)], None)
# /usr/include/GL/glu.h:281
gluBuild1DMipmaps = _link_function('gluBuild1DMipmaps', GLint, [GLenum, GLint, GLsizei, GLenum, GLenum, POINTER(None)], None)
# /usr/include/GL/glu.h:282
gluBuild2DMipmapLevels = _link_function('gluBuild2DMipmapLevels', GLint, [GLenum, GLint, GLsizei, GLsizei, GLenum, GLenum, GLint, GLint, GLint, POINTER(None)], None)
# /usr/include/GL/glu.h:283
gluBuild2DMipmaps = _link_function('gluBuild2DMipmaps', GLint, [GLenum, GLint, GLsizei, GLsizei, GLenum, GLenum, POINTER(None)], None)
# /usr/include/GL/glu.h:284
gluBuild3DMipmapLevels = _link_function('gluBuild3DMipmapLevels', GLint, [GLenum, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, GLint, GLint, GLint, POINTER(None)], None)
# /usr/include/GL/glu.h:285
gluBuild3DMipmaps = _link_function('gluBuild3DMipmaps', GLint, [GLenum, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, POINTER(None)], None)
GLboolean = c_ubyte # /usr/include/GL/gl.h:54
GLubyte = c_ubyte # /usr/include/GL/gl.h:60
# /usr/include/GL/glu.h:286
gluCheckExtension = _link_function('gluCheckExtension', GLboolean, [POINTER(GLubyte), POINTER(GLubyte)], None)
GLdouble = c_double # /usr/include/GL/gl.h:65
# /usr/include/GL/glu.h:287
gluCylinder = _link_function('gluCylinder', None, [POINTER(GLUquadric), GLdouble, GLdouble, GLdouble, GLint, GLint], None)
# /usr/include/GL/glu.h:288
gluDeleteNurbsRenderer = _link_function('gluDeleteNurbsRenderer', None, [POINTER(GLUnurbs)], None)
# /usr/include/GL/glu.h:289
gluDeleteQuadric = _link_function('gluDeleteQuadric', None, [POINTER(GLUquadric)], None)
# /usr/include/GL/glu.h:290
gluDeleteTess = _link_function('gluDeleteTess', None, [POINTER(GLUtesselator)], None)
# /usr/include/GL/glu.h:291
gluDisk = _link_function('gluDisk', None, [POINTER(GLUquadric), GLdouble, GLdouble, GLint, GLint], None)
# /usr/include/GL/glu.h:292
gluEndCurve = _link_function('gluEndCurve', None, [POINTER(GLUnurbs)], None)
# /usr/include/GL/glu.h:293
gluEndPolygon = _link_function('gluEndPolygon', None, [POINTER(GLUtesselator)], None)
# /usr/include/GL/glu.h:294
gluEndSurface = _link_function('gluEndSurface', None, [POINTER(GLUnurbs)], None)
# /usr/include/GL/glu.h:295
gluEndTrim = _link_function('gluEndTrim', None, [POINTER(GLUnurbs)], None)
# /usr/include/GL/glu.h:296
gluErrorString = _link_function('gluErrorString', POINTER(GLubyte), [GLenum], None)
GLfloat = c_float # /usr/include/GL/gl.h:63
# /usr/include/GL/glu.h:297
gluGetNurbsProperty = _link_function('gluGetNurbsProperty', None, [POINTER(GLUnurbs), GLenum, POINTER(GLfloat)], None)
# /usr/include/GL/glu.h:298
gluGetString = _link_function('gluGetString', POINTER(GLubyte), [GLenum], None)
# /usr/include/GL/glu.h:299
gluGetTessProperty = _link_function('gluGetTessProperty', None, [POINTER(GLUtesselator), GLenum, POINTER(GLdouble)], None)
# /usr/include/GL/glu.h:300
gluLoadSamplingMatrices = _link_function('gluLoadSamplingMatrices', None, [POINTER(GLUnurbs), POINTER(GLfloat), POINTER(GLfloat), POINTER(GLint)], None)
# /usr/include/GL/glu.h:301
gluLookAt = _link_function('gluLookAt', None, [GLdouble, GLdouble, GLdouble, GLdouble, GLdouble, GLdouble, GLdouble, GLdouble, GLdouble], None)
# /usr/include/GL/glu.h:302
gluNewNurbsRenderer = _link_function('gluNewNurbsRenderer', POINTER(GLUnurbs), [], None)
# /usr/include/GL/glu.h:303
gluNewQuadric = _link_function('gluNewQuadric', POINTER(GLUquadric), [], None)
# /usr/include/GL/glu.h:304
gluNewTess = _link_function('gluNewTess', POINTER(GLUtesselator), [], None)
# /usr/include/GL/glu.h:305
gluNextContour = _link_function('gluNextContour', None, [POINTER(GLUtesselator), GLenum], None)
# /usr/include/GL/glu.h:306
gluNurbsCallback = _link_function('gluNurbsCallback', None, [POINTER(GLUnurbs), GLenum, _GLUfuncptr], None)
GLvoid = None # /usr/include/GL/gl.h:67
# /usr/include/GL/glu.h:307
gluNurbsCallbackData = _link_function('gluNurbsCallbackData', None, [POINTER(GLUnurbs), POINTER(GLvoid)], None)
# /usr/include/GL/glu.h:308
gluNurbsCallbackDataEXT = _link_function('gluNurbsCallbackDataEXT', None, [POINTER(GLUnurbs), POINTER(GLvoid)], None)
# /usr/include/GL/glu.h:309
gluNurbsCurve = _link_function('gluNurbsCurve', None, [POINTER(GLUnurbs), GLint, POINTER(GLfloat), GLint, POINTER(GLfloat), GLint, GLenum], None)
# /usr/include/GL/glu.h:310
gluNurbsProperty = _link_function('gluNurbsProperty', None, [POINTER(GLUnurbs), GLenum, GLfloat], None)
# /usr/include/GL/glu.h:311
gluNurbsSurface = _link_function('gluNurbsSurface', None, [POINTER(GLUnurbs), GLint, POINTER(GLfloat), GLint, POINTER(GLfloat), GLint, GLint, POINTER(GLfloat), GLint, GLint, GLenum], None)
# /usr/include/GL/glu.h:312
gluOrtho2D = _link_function('gluOrtho2D', None, [GLdouble, GLdouble, GLdouble, GLdouble], None)
# /usr/include/GL/glu.h:313
gluPartialDisk = _link_function('gluPartialDisk', None, [POINTER(GLUquadric), GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble], None)
# /usr/include/GL/glu.h:314
gluPerspective = _link_function('gluPerspective', None, [GLdouble, GLdouble, GLdouble, GLdouble], None)
# /usr/include/GL/glu.h:315
gluPickMatrix = _link_function('gluPickMatrix', None, [GLdouble, GLdouble, GLdouble, GLdouble, POINTER(GLint)], None)
# /usr/include/GL/glu.h:316
gluProject = _link_function('gluProject', GLint, [GLdouble, GLdouble, GLdouble, POINTER(GLdouble), POINTER(GLdouble), POINTER(GLint), POINTER(GLdouble), POINTER(GLdouble), POINTER(GLdouble)], None)
# /usr/include/GL/glu.h:317
gluPwlCurve = _link_function('gluPwlCurve', None, [POINTER(GLUnurbs), GLint, POINTER(GLfloat), GLint, GLenum], None)
# /usr/include/GL/glu.h:318
gluQuadricCallback = _link_function('gluQuadricCallback', None, [POINTER(GLUquadric), GLenum, _GLUfuncptr], None)
# /usr/include/GL/glu.h:319
gluQuadricDrawStyle = _link_function('gluQuadricDrawStyle', None, [POINTER(GLUquadric), GLenum], None)
# /usr/include/GL/glu.h:320
gluQuadricNormals = _link_function('gluQuadricNormals', None, [POINTER(GLUquadric), GLenum], None)
# /usr/include/GL/glu.h:321
gluQuadricOrientation = _link_function('gluQuadricOrientation', None, [POINTER(GLUquadric), GLenum], None)
# /usr/include/GL/glu.h:322
gluQuadricTexture = _link_function('gluQuadricTexture', None, [POINTER(GLUquadric), GLboolean], None)
# /usr/include/GL/glu.h:323
gluScaleImage = _link_function('gluScaleImage', GLint, [GLenum, GLsizei, GLsizei, GLenum, POINTER(None), GLsizei, GLsizei, GLenum, POINTER(GLvoid)], None)
# /usr/include/GL/glu.h:324
gluSphere = _link_function('gluSphere', None, [POINTER(GLUquadric), GLdouble, GLint, GLint], None)
# /usr/include/GL/glu.h:325
gluTessBeginContour = _link_function('gluTessBeginContour', None, [POINTER(GLUtesselator)], None)
# /usr/include/GL/glu.h:326
gluTessBeginPolygon = _link_function('gluTessBeginPolygon', None, [POINTER(GLUtesselator), POINTER(GLvoid)], None)
# /usr/include/GL/glu.h:327
gluTessCallback = _link_function('gluTessCallback', None, [POINTER(GLUtesselator), GLenum, _GLUfuncptr], None)
# /usr/include/GL/glu.h:328
gluTessEndContour = _link_function('gluTessEndContour', None, [POINTER(GLUtesselator)], None)
# /usr/include/GL/glu.h:329
gluTessEndPolygon = _link_function('gluTessEndPolygon', None, [POINTER(GLUtesselator)], None)
# /usr/include/GL/glu.h:330
gluTessNormal = _link_function('gluTessNormal', None, [POINTER(GLUtesselator), GLdouble, GLdouble, GLdouble], None)
# /usr/include/GL/glu.h:331
gluTessProperty = _link_function('gluTessProperty', None, [POINTER(GLUtesselator), GLenum, GLdouble], None)
# /usr/include/GL/glu.h:332
gluTessVertex = _link_function('gluTessVertex', None, [POINTER(GLUtesselator), POINTER(GLdouble), POINTER(GLvoid)], None)
# /usr/include/GL/glu.h:333
gluUnProject = _link_function('gluUnProject', GLint, [GLdouble, GLdouble, GLdouble, POINTER(GLdouble), POINTER(GLdouble), POINTER(GLint), POINTER(GLdouble), POINTER(GLdouble), POINTER(GLdouble)], None)
# /usr/include/GL/glu.h:334
gluUnProject4 = _link_function('gluUnProject4', GLint, [GLdouble, GLdouble, GLdouble, GLdouble, POINTER(GLdouble), POINTER(GLdouble), POINTER(GLint), GLdouble, GLdouble, POINTER(GLdouble), POINTER(GLdouble), POINTER(GLdouble), POINTER(GLdouble)], None)
__all__ = ['GLU_EXT_object_space_tess', 'GLU_EXT_nurbs_tessellator',
'GLU_FALSE', 'GLU_TRUE', 'GLU_VERSION_1_1', 'GLU_VERSION_1_2',
'GLU_VERSION_1_3', 'GLU_VERSION', 'GLU_EXTENSIONS', 'GLU_INVALID_ENUM',
'GLU_INVALID_VALUE', 'GLU_OUT_OF_MEMORY', 'GLU_INCOMPATIBLE_GL_VERSION',
'GLU_INVALID_OPERATION', 'GLU_OUTLINE_POLYGON', 'GLU_OUTLINE_PATCH',
'GLU_NURBS_ERROR', 'GLU_ERROR', 'GLU_NURBS_BEGIN', 'GLU_NURBS_BEGIN_EXT',
'GLU_NURBS_VERTEX', 'GLU_NURBS_VERTEX_EXT', 'GLU_NURBS_NORMAL',
'GLU_NURBS_NORMAL_EXT', 'GLU_NURBS_COLOR', 'GLU_NURBS_COLOR_EXT',
'GLU_NURBS_TEXTURE_COORD', 'GLU_NURBS_TEX_COORD_EXT', 'GLU_NURBS_END',
'GLU_NURBS_END_EXT', 'GLU_NURBS_BEGIN_DATA', 'GLU_NURBS_BEGIN_DATA_EXT',
'GLU_NURBS_VERTEX_DATA', 'GLU_NURBS_VERTEX_DATA_EXT', 'GLU_NURBS_NORMAL_DATA',
'GLU_NURBS_NORMAL_DATA_EXT', 'GLU_NURBS_COLOR_DATA',
'GLU_NURBS_COLOR_DATA_EXT', 'GLU_NURBS_TEXTURE_COORD_DATA',
'GLU_NURBS_TEX_COORD_DATA_EXT', 'GLU_NURBS_END_DATA',
'GLU_NURBS_END_DATA_EXT', 'GLU_NURBS_ERROR1', 'GLU_NURBS_ERROR2',
'GLU_NURBS_ERROR3', 'GLU_NURBS_ERROR4', 'GLU_NURBS_ERROR5',
'GLU_NURBS_ERROR6', 'GLU_NURBS_ERROR7', 'GLU_NURBS_ERROR8',
'GLU_NURBS_ERROR9', 'GLU_NURBS_ERROR10', 'GLU_NURBS_ERROR11',
'GLU_NURBS_ERROR12', 'GLU_NURBS_ERROR13', 'GLU_NURBS_ERROR14',
'GLU_NURBS_ERROR15', 'GLU_NURBS_ERROR16', 'GLU_NURBS_ERROR17',
'GLU_NURBS_ERROR18', 'GLU_NURBS_ERROR19', 'GLU_NURBS_ERROR20',
'GLU_NURBS_ERROR21', 'GLU_NURBS_ERROR22', 'GLU_NURBS_ERROR23',
'GLU_NURBS_ERROR24', 'GLU_NURBS_ERROR25', 'GLU_NURBS_ERROR26',
'GLU_NURBS_ERROR27', 'GLU_NURBS_ERROR28', 'GLU_NURBS_ERROR29',
'GLU_NURBS_ERROR30', 'GLU_NURBS_ERROR31', 'GLU_NURBS_ERROR32',
'GLU_NURBS_ERROR33', 'GLU_NURBS_ERROR34', 'GLU_NURBS_ERROR35',
'GLU_NURBS_ERROR36', 'GLU_NURBS_ERROR37', 'GLU_AUTO_LOAD_MATRIX',
'GLU_CULLING', 'GLU_SAMPLING_TOLERANCE', 'GLU_DISPLAY_MODE',
'GLU_PARAMETRIC_TOLERANCE', 'GLU_SAMPLING_METHOD', 'GLU_U_STEP', 'GLU_V_STEP',
'GLU_NURBS_MODE', 'GLU_NURBS_MODE_EXT', 'GLU_NURBS_TESSELLATOR',
'GLU_NURBS_TESSELLATOR_EXT', 'GLU_NURBS_RENDERER', 'GLU_NURBS_RENDERER_EXT',
'GLU_OBJECT_PARAMETRIC_ERROR', 'GLU_OBJECT_PARAMETRIC_ERROR_EXT',
'GLU_OBJECT_PATH_LENGTH', 'GLU_OBJECT_PATH_LENGTH_EXT', 'GLU_PATH_LENGTH',
'GLU_PARAMETRIC_ERROR', 'GLU_DOMAIN_DISTANCE', 'GLU_MAP1_TRIM_2',
'GLU_MAP1_TRIM_3', 'GLU_POINT', 'GLU_LINE', 'GLU_FILL', 'GLU_SILHOUETTE',
'GLU_SMOOTH', 'GLU_FLAT', 'GLU_NONE', 'GLU_OUTSIDE', 'GLU_INSIDE',
'GLU_TESS_BEGIN', 'GLU_BEGIN', 'GLU_TESS_VERTEX', 'GLU_VERTEX',
'GLU_TESS_END', 'GLU_END', 'GLU_TESS_ERROR', 'GLU_TESS_EDGE_FLAG',
'GLU_EDGE_FLAG', 'GLU_TESS_COMBINE', 'GLU_TESS_BEGIN_DATA',
'GLU_TESS_VERTEX_DATA', 'GLU_TESS_END_DATA', 'GLU_TESS_ERROR_DATA',
'GLU_TESS_EDGE_FLAG_DATA', 'GLU_TESS_COMBINE_DATA', 'GLU_CW', 'GLU_CCW',
'GLU_INTERIOR', 'GLU_EXTERIOR', 'GLU_UNKNOWN', 'GLU_TESS_WINDING_RULE',
'GLU_TESS_BOUNDARY_ONLY', 'GLU_TESS_TOLERANCE', 'GLU_TESS_ERROR1',
'GLU_TESS_ERROR2', 'GLU_TESS_ERROR3', 'GLU_TESS_ERROR4', 'GLU_TESS_ERROR5',
'GLU_TESS_ERROR6', 'GLU_TESS_ERROR7', 'GLU_TESS_ERROR8',
'GLU_TESS_MISSING_BEGIN_POLYGON', 'GLU_TESS_MISSING_BEGIN_CONTOUR',
'GLU_TESS_MISSING_END_POLYGON', 'GLU_TESS_MISSING_END_CONTOUR',
'GLU_TESS_COORD_TOO_LARGE', 'GLU_TESS_NEED_COMBINE_CALLBACK',
'GLU_TESS_WINDING_ODD', 'GLU_TESS_WINDING_NONZERO',
'GLU_TESS_WINDING_POSITIVE', 'GLU_TESS_WINDING_NEGATIVE',
'GLU_TESS_WINDING_ABS_GEQ_TWO', 'GLUnurbs', 'GLUquadric', 'GLUtesselator',
'GLUnurbsObj', 'GLUquadricObj', 'GLUtesselatorObj', 'GLUtriangulatorObj',
'GLU_TESS_MAX_COORD', '_GLUfuncptr', 'gluBeginCurve', 'gluBeginPolygon',
'gluBeginSurface', 'gluBeginTrim', 'gluBuild1DMipmapLevels',
'gluBuild1DMipmaps', 'gluBuild2DMipmapLevels', 'gluBuild2DMipmaps',
'gluBuild3DMipmapLevels', 'gluBuild3DMipmaps', 'gluCheckExtension',
'gluCylinder', 'gluDeleteNurbsRenderer', 'gluDeleteQuadric', 'gluDeleteTess',
'gluDisk', 'gluEndCurve', 'gluEndPolygon', 'gluEndSurface', 'gluEndTrim',
'gluErrorString', 'gluGetNurbsProperty', 'gluGetString', 'gluGetTessProperty',
'gluLoadSamplingMatrices', 'gluLookAt', 'gluNewNurbsRenderer',
'gluNewQuadric', 'gluNewTess', 'gluNextContour', 'gluNurbsCallback',
'gluNurbsCallbackData', 'gluNurbsCallbackDataEXT', 'gluNurbsCurve',
'gluNurbsProperty', 'gluNurbsSurface', 'gluOrtho2D', 'gluPartialDisk',
'gluPerspective', 'gluPickMatrix', 'gluProject', 'gluPwlCurve',
'gluQuadricCallback', 'gluQuadricDrawStyle', 'gluQuadricNormals',
'gluQuadricOrientation', 'gluQuadricTexture', 'gluScaleImage', 'gluSphere',
'gluTessBeginContour', 'gluTessBeginPolygon', 'gluTessCallback',
'gluTessEndContour', 'gluTessEndPolygon', 'gluTessNormal', 'gluTessProperty',
'gluTessVertex', 'gluUnProject', 'gluUnProject4']
# END GENERATED CONTENT (do not edit above this line)
| 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.