Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
paddywwoof committed Nov 25, 2013
2 parents 09ee114 + 54543c8 commit 4c1dc75
Show file tree
Hide file tree
Showing 9 changed files with 93 additions and 89 deletions.
52 changes: 25 additions & 27 deletions pi3d/Buffer.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals

import ctypes, itertools
import numpy as np

from ctypes import c_float, c_int

Expand Down Expand Up @@ -65,31 +66,26 @@ def __init__(self, shape, pts, texcoords, faces, normals=None, smooth=True):
"""
#self.shape = shape
self.textures = []
pts = np.array(pts)
texcoords = np.array(texcoords)
faces = np.array(faces)

if normals == None: #i.e. normals will only be generated if explictly None
LOGGER.debug('Calculating normals ...')

normals = [[] for p in pts]
# Calculate normals.
for f in faces:
a, b, c = f[0:3]

ab = Utility.vec_sub(pts[a], pts[b])
bc = Utility.vec_sub(pts[a], pts[c])
n = tuple(Utility.vec_normal(Utility.vec_cross(ab, bc)))
for x in f[0:3]:
normals[x].append(n)

for i, n in enumerate(normals):
if n:
if smooth:
norms = [sum(v[k] for v in n) for k in range(3)]
else: # This should be slightly faster for large shapes
norms = [n[0][k] for k in range(3)]
normals[i] = tuple(Utility.vec_normal(norms))
else:
normals[i] = 0, 0, 0.01
normals = np.zeros(pts.shape, dtype=pts.dtype) #empty array rights size

fv = pts[faces] #expand faces with x,y,z values for each vertex
#cross product of two edges of triangles
fn = np.cross(fv[:][:][:,1] - fv[:][:][:,0], fv[:][:][:,2] - fv[:][:][:,0])
fn = Utility.normalize_v3(fn)
normals[faces[:,0]] += fn #add up all normal vectors for a vertex
normals[faces[:,1]] += fn
normals[faces[:,2]] += fn
Utility.normalize_v3(normals)
else:
normals = np.array(normals)

# keep a copy for speeding up the collision testing of ElevationMap
self.vertices = pts
self.normals = normals
Expand All @@ -102,19 +98,18 @@ def __init__(self, shape, pts, texcoords, faces, normals=None, smooth=True):
if len(texcoords) != n_verts:
if len(normals) != n_verts:
self.N_BYTES = 12 # only use pts
self.array_buffer = c_floats(list(itertools.chain(*pts)))
self.array_buffer = c_floats(pts.reshape(-1))
else:
self.N_BYTES = 24 # use pts and normals
points = [p + n for p, n in zip(pts, normals)]
self.array_buffer = c_floats(list(itertools.chain(*points)))
self.array_buffer = c_floats(np.concatenate((pts, normals),
axis=1).reshape(-1))
else:
self.N_BYTES = 32 # use all three NB doesn't check that normals are there
points = [p + n + t for p, n, t in zip(pts, normals, texcoords)]
self.array_buffer = c_floats(list(itertools.chain(*points)))
self.array_buffer = c_floats(np.concatenate((pts, normals, texcoords),
axis=1).reshape(-1))

self.ntris = len(faces)
points = [f[0:3] for f in faces]
self.element_array_buffer = c_shorts(list(itertools.chain(*points)))
self.element_array_buffer = c_shorts(faces.reshape(-1))

def __del__(self):
#super(Buffer, self).__del__() #TODO supposed to always call super.__del__
Expand Down Expand Up @@ -208,6 +203,9 @@ def set_draw_details(self, shader, textures, ntiles=0.0, shiny=0.0,
def set_material(self, mtrl):
self.unib[3:6] = mtrl[0:3]

def set_textures(self, textures):
self.textures = textures

def set_offset(self, offset=(0.0, 0.0)):
self.unib[9:11] = offset

Expand Down
9 changes: 8 additions & 1 deletion pi3d/Texture.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,14 @@ class Texture(Loadable):
"""loads an image file from disk and converts it into an array that
can be used by shaders. It inherits from Loadable in order that the
file access work can happen in another thread. and the conversion
to opengl format can happen just in time when tex() is first called
to opengl format can happen just in time when tex() is first called.
NB images loaded as textures can cause distortion effects unless they
are certain sizes (below). **If the image width is a value not in this
list then it will be rescaled with a resulting loss of clarity**
Allowed widths 4, 8, 16, 32, 48, 64, 72, 96, 128, 144, 192, 256, 288,
384, 512, 576, 640, 720, 768, 800, 960, 1024, 1080, 1920
"""
def __init__(self, file_string, blend=False, flip=False, size=0,
defer=DEFER_TEXTURE_LOADING, mipmap=True):
Expand Down
10 changes: 6 additions & 4 deletions pi3d/event/Event.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,21 +64,23 @@ def __init__(self, keyboardHandler=None, mouseHandler=None, joystickHandler=None
self.streams = [ ]
if wantKeyboard:
keyboards = find_devices("kbd")
self.streams += map(lambda x: EventStream(x, "keyboard"), keyboards)
for x in keyboards:
self.streams.append(EventStream(x, "keyboard"))
else:
keyboards = [ ]
print("keyboards =", keyboards)
if wantMouse:
mice = find_devices("mouse", butNot=keyboards)
for x in mice:
self.streams.append(EventStream(x, "mouse"))
print("mice = ", mice)
self.streams += map(lambda x: EventStream(x, "mouse"), mice)
else:
mice = [ ]
if wantJoystick:
joysticks = find_devices("js", butNot=keyboards+mice)
for x in joysticks:
self.streams.append(EventStream(x, "joystick"))
print("joysticks =", joysticks)
js_streams = map(lambda x: EventStream(x, "joystick"), joysticks)
self.streams += js_streams
for x in self.streams:
x.acquire_abs_info()

Expand Down
16 changes: 9 additions & 7 deletions pi3d/event/EventStream.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,10 @@ def grab_by_type(self, deviceType, deviceIndex=None, grab=True, streams=None):
if streams == None:
streams = EventStream.AllStreams

reqdStreams = filter(lambda x: x.deviceType == deviceType and (deviceIndex == None or x.deviceIndex == deviceIndex), streams)
map(lambda x: x.grab(grab), reqdStreams)
for x in streams:
if x.deviceType == deviceType and (deviceIndex == None or
x.deviceIndex == deviceIndex):
x.grab(grab)

@classmethod
def allNext(cls, streams=None):
Expand All @@ -162,18 +164,14 @@ def allNext(cls, streams=None):
If the streams parameter is not given, then all streams are selected.
"""
#print EventStream.AllStreams
#print map(lambda x: x.filehandle, EventStream.AllStreams)
if streams == None:
streams = EventStream.AllStreams

selectlist = map(lambda x: x.filehandle, streams)

selectlist = [x.filehandle for x in streams]
ready = select.select(selectlist, [ ], [ ], 0)[0]
if not ready: return
while ready:
for fd in ready:
stream = list(filter(lambda x: x.filehandle == fd, streams))[0]
try:
s = os.read(fd, Format.EventSize)
except Exception as e:
Expand All @@ -186,6 +184,10 @@ def allNext(cls, streams=None):
failed.add(fd)
continue
if s:
for x in streams:
if x.filehandle == fd:
stream = x
break
event = EventStruct.EventStruct(stream)
event.decode(s)
yield event
Expand Down
2 changes: 1 addition & 1 deletion pi3d/event/EventStruct.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,6 @@ def decode(self, s):
A binary structure packed into a string.
"""
(tsec, tfrac, self.eventType, self.eventCode,
self.eventValue) = struct.unpack(Format.Event,s)
self.eventValue) = struct.unpack(Format.Event, s)

self.time = tsec + tfrac / 1000000.0
22 changes: 5 additions & 17 deletions pi3d/shape/MergeShape.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from pi3d.Buffer import Buffer

from pi3d.Shape import Shape
from pi3d.util.RotateVec import rotate_vec_x, rotate_vec_y, rotate_vec_z
from pi3d.util.RotateVec import rotate_vec

class MergeShape(Shape):
""" 3d model inherits from Shape. As there is quite a time penalty for
Expand Down Expand Up @@ -39,8 +39,7 @@ def __init__(self, camera=None, light=None, name="",
self.indices = [] #stores all indices for single render

self.buf = []
self.buf.append(Buffer(self, self.vertices, self.tex_coords, self.indices,
self.normals))
self.buf.append(Buffer(self, self.vertices, self.tex_coords, self.indices, self.normals))

def merge(self, bufr, x=0.0, y=0.0, z=0.0,
rx=0.0, ry=0.0, rz=0.0,
Expand Down Expand Up @@ -80,22 +79,12 @@ def merge(self, bufr, x=0.0, y=0.0, z=0.0,
original_vertex_count = len(self.vertices)

for v in range(0, len(bufr.vertices)):
def rotate_slice(array):
vec = array[v]
if b[6]:
vec = rotate_vec_z(b[6], vec)
if b[4]:
vec = rotate_vec_x(b[4], vec)
if b[5]:
vec = rotate_vec_y(b[5], vec)
return vec

# Scale, offset and store vertices
vx, vy, vz = rotate_slice(bufr.vertices)
vx, vy, vz = rotate_vec(b[4], b[5], b[6], bufr.vertices[v])
self.vertices.append((vx * b[7] + b[1], vy * b[8] + b[2], vz * b[9] + b[3]))

# Rotate normals
self.normals.append(rotate_slice(bufr.normals))
self.normals.append(rotate_vec(b[4], b[5], b[6], bufr.normals[v]))

self.tex_coords.extend(bufr.tex_coords)

Expand All @@ -105,8 +94,7 @@ def rotate_slice(array):
self.indices.extend(indices)

self.buf = []
self.buf.append(Buffer(self, self.vertices, self.tex_coords, self.indices,
self.normals))
self.buf.append(Buffer(self, self.vertices, self.tex_coords, self.indices, self.normals))

def add(self, bufr, x=0.0, y=0.0, z=0.0, rx=0.0, ry=0.0, rz=0.0,
sx=1.0, sy=1.0, sz=1.0):
Expand Down
6 changes: 3 additions & 3 deletions pi3d/util/Font.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class Font(Texture):

def __init__(self, font, color=(255,255,255,255), codepoints=None,
add_codepoints=None, font_size=48, image_size=512,
italic_adjustment=1.1):
italic_adjustment=1.1, background_color=None):
"""Arguments:
*font*:
File path/name to a TrueType font file.
Expand Down Expand Up @@ -96,7 +96,7 @@ def __init__(self, font, color=(255,255,255,255), codepoints=None,

all_fits = False
while image_size < MAX_SIZE and not all_fits:
self.im = Image.new("RGBA", (image_size, image_size))
self.im = Image.new("RGBA", (image_size, image_size), background_color)
self.alpha = True
self.ix, self.iy = image_size, image_size

Expand All @@ -122,7 +122,7 @@ def __init__(self, font, color=(255,255,255,255), codepoints=None,

if curX + chwidth * italic_adjustment >= image_size:
curX = 0.0
curY += self.height
curY += self.height + 1.0 #leave 1 pixel gap
if curY >= image_size: #run out of space try again with bigger img
all_fits = False
image_size += 256
Expand Down
16 changes: 8 additions & 8 deletions pi3d/util/RotateVec.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,24 @@
"""Calculate position or direction 3D vector after rotation about axis"""
def rotate_vec(rx, ry, rz, xyz):
x, y, z = xyz
if rx:
ca, sa = from_polar(rx)
yy = y * ca - z * sa
z = y * sa + z * ca
y = yy

if ry:
ca, sa = from_polar(ry)
zz = z * ca - x * sa
x = z * sa + x * ca
z = zz

if rx:
ca, sa = from_polar(rx)
yy = y * ca - z * sa
z = y * sa + z * ca
y = yy
if rz:
ca, sa = from_polar(rz)
xx = x * ca - y * sa
y = x * sa + y * ca
x = xx

return x, y, z
"""
# no longer used anywhere
def rotate_vec_x(r, xyz):
ca, sa = from_polar(r)
Expand All @@ -34,3 +33,4 @@ def rotate_vec_y(r, xyz):
def rotate_vec_z(r, xyz):
ca, sa = from_polar(r)
return xyz[0] * ca - xyz[1] * sa, xyz[0] * sa + xyz[1] * ca, xyz[2]
"""
Loading

0 comments on commit 4c1dc75

Please sign in to comment.