Example #1
0
def getPhraseInstructions(sample,
                          start,
                          beats,
                          ms_per_beat,
                          volumeRange=(0.0, 1.0),
                          tempoRange=(1.0, 1.0),
                          panRange=(-1.0, 1.0),
                          roundTo=1):
    ms = 0
    duration = beats * ms_per_beat
    instructions = []
    tempoFrom, tempoTo = tempoRange
    tempoRange = (int(round(ms_per_beat / tempoFrom)),
                  int(round(ms_per_beat / tempoTo)))
    while ms < duration:
        pos = 1.0 * ms / duration
        pos = -(math.cos(math.pi * 2.0 * pos) - 1) / 2.0  # sin curve in-out
        volume = lerp(volumeRange, pos)
        pan = lerp(panRange, pos)
        instructions.append({
            "sound": sample["parent"],
            "start": ms + start,
            "clipStart": sample["start"],
            "clipDur": sample["dur"],
            "volume": volume,
            "pan": pan
        })
        addMs = int(roundToNearest(lerp(tempoRange, pos), roundTo))
        addMs = max(addMs, roundTo)
        ms += addMs
    return instructions
Example #2
0
def lerp(x, x0, x1, c0, c1):
    """Linear interpolation of 24-bit color values.  Given a value x within
    the range x0, x1 and colors c0, c1 this will return a color c that is
    linearly interpolated within c0, c1 proportional to x within x0, x1.
    """
    r0, g0, b0 = decompose(c0)
    r1, g1, b1 = decompose(c1)
    return compose(utils.clamp(int(utils.lerp(x, x0, x1, r0, r1)), 0, 255),
                   utils.clamp(int(utils.lerp(x, x0, x1, g0, g1)), 0, 255),
                   utils.clamp(int(utils.lerp(x, x0, x1, b0, b1)), 0, 255))
Example #3
0
  def generate(self, fn, view):
    self.uvmap = []

    for j in range(self.height):
      for i in range(self.width):
        x = lerp(view[0], view[1], float(i) / self.width)
        y = lerp(view[2], view[3], float(j) / self.height)

        (u, v) = fn(x, y)

        self.uvmap.append((int(u * 256) & 255, int(v * 256) & 255))
Example #4
0
def Neon1(i, j):
    x = lerp(-1.5, 1.5, float(i) / width)
    y = lerp(-2.0, -0.5, float(j) / height)

    # a = atan2(x, y)
    r = dist(x, y, 0.0, 0.0)

    if r == 0:
        return 0

    return int(512 / r)
Example #5
0
def Neon2(i, j):
    x = lerp(-1.0, 1.0, float(i) / width)
    y = lerp(-1.0, 1.0, float(j) / height)

    a = atan2(x, y)
    r = dist(x, y, 0.0, 0.0) + 0.2 * sin(7 * a)

    if r == 0:
        return 0

    return int(16 / r)
Example #6
0
def Neon2(i, j):
    x = lerp(-1.0, 1.0, float(i) / width)
    y = lerp(-1.0, 1.0, float(j) / height)

    a = atan2(x, y)
    r = dist(x, y, 0.0, 0.0) + 0.2 * sin(7 * a)

    if r == 0:
        return 0

    return int(16 / r)
Example #7
0
def Neon1(i, j):
    x = lerp(-1.5, 1.5, float(i) / width)
    y = lerp(-2.0, -0.5, float(j) / height)

    # a = atan2(x, y)
    r = dist(x, y, 0.0, 0.0)

    if r == 0:
        return 0

    return int(512 / r)
Example #8
0
 def _sparkle_animation(self):
     n = len(self._lights)
     phases = [random.uniform(0, 2.0*math.pi) for _ in range(n)]
     f = self.happiness_freq
     frequencies = [random.uniform(f/2.0, 2.0*f) for _ in range(n)]
     while True:
         t = time.time()
         for i in range(n):
             x = math.sin(2.0*math.pi*frequencies[i]*t + phases[i])
             hue = utils.lerp(x, -1.0, 1.0, 0.0, 360.0)
             x = math.sin(2.0*math.pi*frequencies[-(i+1)]*t + phases[-(i+1)])
             value = utils.lerp(x, -1.0, 1.0, 0, self.brightness_hsv)
             yield color.hsv_to_rgb(hue, 1.0, value)
Example #9
0
def Neon3(i, j):
    x = lerp(-1.0, 1.0, float(i) / width)
    y = lerp(-0.8, 1.2, float(j) / height)

    a = atan2(x, y)
    r = dist(x, y, 0.0, 0.0) + 0.2 * saw(5.0 * a /
                                         (2.0 * pi)) + 0.1 * abs(sin(5.0 * a))
    # r = dist(x, y, 0.0, 0.0) + 0.2 * abs(sin(5.0 * a))

    if r == 0:
        return 0

    return int(r * 64)
Example #10
0
def Neon3(i, j):
    x = lerp(-1.0, 1.0, float(i) / width)
    y = lerp(-0.8, 1.2, float(j) / height)

    a = atan2(x, y)
    r = dist(x, y, 0.0, 0.0) + 0.2 * saw(5.0 * a /
                                         (2.0 * pi)) + 0.1 * abs(sin(5.0 * a))
    #r = dist(x, y, 0.0, 0.0) + 0.2 * abs(sin(5.0 * a))

    if r == 0:
        return 0

    return int(r * 64)
 def findpath(self):
     # determine where the start and end path are and then find all
     # consecutive paths between the start and end.
     start = end = None
     for x in range(BOARD_WIDTH):
         for y in range(BOARD_HEIGHT):
             if self.get(x,y) == "pathstart":
                 start = (x,y)
             elif self.get(x,y) == "pathend":
                 end = (x,y)
     if (start != None and end != None):
         # find path from start to end.
         current = start
         mapsolution = []
         while current != end:
             mapsolution.append(current)
             #find a cell up, down, left or right of our current that's not in used_paths.
             testcells = [(current[0]-1, current[1]), (current[0],current[1]-1), (current[0]+1, current[1]), (current[0], current[1]+1)]
             for cell in testcells:
                 if cell not in mapsolution and 0 < cell[0] < BOARD_WIDTH and 0 < cell[1] < BOARD_HEIGHT and self.get(cell[0], cell[1]) in ["pathstart", "pathend", "path"]:
                     current = cell
                     break
         mapsolution.append(end)
     solution = []
     #convert solution to screen coordinates
     #path.append(basepath.pop(0))
     while len(mapsolution) > 1:
         solution.extend(utils.lerp((mapsolution[0][0]*CELL_SIZE, mapsolution[0][1]*CELL_SIZE), \
                                (mapsolution[1][0]*CELL_SIZE, mapsolution[1][1]*CELL_SIZE)))
         mapsolution.pop(0)
     return solution
Example #12
0
 def _knight_rider_animation(self):
     n = len(self._lights)
     while True:
         t = time.time()
         f = self.happiness_freq
         x0 = math.sin(2.0*math.pi*f*t)
         x1 = math.sin(2.0*math.pi*f*t - math.pi*(1/n))
         i0 = int(utils.lerp(x0, -1.0, 1.0, 0, n))
         i1 = int(utils.lerp(x1, -1.0, 1.0, 0, n))
         for i in range(n):
             if i == i0:
                 yield color.hsv_to_rgb(self.hue, 1.0, self.brightness_hsv)
             elif i == i1:
                 yield color.hsv_to_rgb(self.hue, 1.0, self.brightness_hsv/2)
             else:
                 yield 0
Example #13
0
 def update(self, delta):
     if self.state == STATE_OPENING:
         self.animTime += delta
         self.y = lerp(self.animStartY, self.animEndY, self.animTime/DOOR_OPEN_TIME)
         if self.animTime >= DOOR_OPEN_TIME:
             self.state = STATE_STILL
             self.y = self.animEndY
Example #14
0
    def get_position_for_wall_lightmap_texel(self, texel):
        """Get the position and normal for the part of the wall that the given
        lightmap texel applies to.
        
        Returns a position tuple (x, y, z) and a float for the normal (angle
        around the z axis; walls are always vertical)
        
        """
        # Get the texel in texture map space (0.0-1.0). Add 0.5 to use the
        # center of the texel instead of the corner.
        map_coords = ((texel[0] + 0.5) / float(self.wall_lightmap.size[0]),
                      (texel[1] + 0.5) / float(self.wall_lightmap.size[1]))
        
        # Find out which wall it's on
        for i, lightmap_wall in enumerate(self.lightmap_walls):
            if lightmap_wall[0] <= map_coords[0] < lightmap_wall[1]:
                break
        else:
            # Texel isn't applied to any wall
            return None
        wall = self.walls[i]
        
        # Find out how far along the wall it is
        ratio = ((map_coords[0] - lightmap_wall[0]) /
                 (lightmap_wall[1] - lightmap_wall[0]))
        # Use this to lerp along the wall
        x = utils.lerp(wall[0][0], wall[1][0], ratio)
        y = utils.lerp(wall[0][1], wall[1][1], ratio)
        
        # Lightmap texture height always reaches from floor to ceiling. Find
        # the z value.
        height_ratio = map_coords[1]
        z = utils.lerp(self.floor_height, self.ceiling_height, height_ratio)

        # Skip texels that won't get drawn (because the geometry is hidden)
        if i in self.shared_walls:
            other = self.shared_walls[i]
            if other.floor_height < z < other.ceiling_height:
                return None
        
        position = x, y, z
        wall_angle = math.atan2(wall[1][1] - wall[0][1], wall[1][0] - wall[0][0])
        normal = wall_angle - math.pi / 2.0
        pitch = 0.0  # No sloped walls
        return position, normal, pitch
 def computeSettings(time, rendererArgs):
     settings = rendererArgs.clone()
     width = pow(
         utils.lerp(time, pow(WIDTH_START, EXPONENT),
                    pow(WIDTH_END, EXPONENT)), 1 / EXPONENT)
     scaling = SCALING_START * WIDTH_START / width
     settings.set_linear_tf(utils.multiIso2Linear(multiiso_tf, width))
     settings.opacity_scaling = scaling
     return settings, width
Example #16
0
 def _pulse_animation():
     while True:
         n = len(self._lights)
         t = time.time()
         x = math.sin(2.0*math.pi*freq_hz*t)
         max_val = self.brightness_hsv
         min_val = 0.75 * max_val
         value = utils.lerp(x, -1.0, 1.0, max_val, min_val)
         for i in range(n):
             yield color.hsv_to_rgb(hue, 1.0, value)
Example #17
0
    def update(self, drag_delta, zoom_delta):
        '''Rotates a set of nested empties to do a 3rd-person camera. The
        parameter drag_delta is a 2D vector of how much to rotate it by or None
        '''
        if drag_delta is not None:
            vel = drag_delta.copy()
            vel *= config.get('MOUSE/SENSITIVITY')
            if config.get('MOUSE/Y_INVERT'):
                vel.y *= -1
        else:
            vel = mathutils.Vector([0, 0])

        # Smooth the mouse motion
        vel = utils.lerp(self.prev_vel, vel, config.get('MOUSE/SMOOTHING'))
        self.prev_vel = vel
        
        zoom_vel = utils.lerp(self.zoom_vel, zoom_delta, config.get('MOUSE/ZOOM_SMOOTHING'))
        self.zoom_vel = zoom_vel

        # Rotate the objects
        self.yaw.applyRotation([0, vel[0], 0], True)
        self.pitch.applyRotation([0, vel[1], 0], True)

        # Stop rotation over the top
        current_rot = self.pitch.localOrientation.to_euler()
        current_rot.y = min(self.config['MAX_ANGLE'], max(self.config['MIN_ANGLE'], current_rot.y))
        self.pitch.localOrientation = current_rot
        
        # Do zooming:
        self.zoom += self.zoom_vel * config.get('MOUSE/ZOOM_SENSITIVITY')
        self.zoom = min(1, max(0, self.zoom))
        self.camera.localPosition.x = utils.lerp(
            self.config['MIN_ZOOM_DIST'],
            self.config['MAX_ZOOM_DIST'],
            self.zoom ** 0.5
        )
        self.camera.fov = utils.lerp(
            self.config['MIN_ZOOM_FOV'],
            self.config['MAX_ZOOM_FOV'],
            self.zoom ** 0.5
        )
        
        sounds.set_listener_transform(self.camera.worldTransform)
Example #18
0
 def _spectrum_animation(self):
     n = len(self._lights)
     while True:
         # Run a FFT on the incoming audio to break it into frequency
         # buckets. Interpolate those as the intensity of hues across the
         # pixels.
         audio = self._microphone.last_read
         if audio is None or len(audio) < 4*n:
             continue
         audio = np.frombuffer(audio[:4*n], dtype='int16')
         freqs = 10*np.log10(np.abs(np.fft.rfft(audio)))
         if len(freqs) < (n+1):
             continue
         max_power = 30.0  #TODO: Auto tune this value?
         max_value = self.brightness_hsv
         for i in range(n):
             hue = utils.lerp(i, 0, n, 0.0, 360.0)
             value = utils.lerp(freqs[i+1], 0, max_power, 0, max_value)
             value = utils.clamp(value, 0, max_value)
             yield color.hsv_to_rgb(hue, 1.0, value)
Example #19
0
 def _idle_animation(self):
     n = len(self._lights)
     while True:
         t = time.time()
         max_val = self.brightness_hsv
         min_val = 0.5 * max_val
         for i in range(n):
             phase = i/(n-1)*2.0*math.pi
             x = math.sin(2.0*math.pi*self.happiness_freq*t + phase)
             value = utils.lerp(x, -1.0, 1.0, max_val, min_val)
             yield color.hsv_to_rgb(self.hue, 1.0, value)
Example #20
0
 def __init__(self, border, tops):
     self.border = border
     self.tops = tops
     self.levels = []
     n = len(tops)
     for i in range(n):
         border = [Vec3(p.x, p.y, p.z + i * 2.5) for p in self.border]
         c = center(border)
         border = [lerp(p, c, 1 - 0.99**i) for p in border]
         top = (i + 1) * 2.5
         level = Level(border=border, top=top, cover=True)
         self.levels.append(level)
Example #21
0
def align_goalposts(point_location, ball_location, left_post, right_post):
    position_to_ball = position_to_ball = (
        ball_location - point_location).normalize().flatten()
    ball_to_goal_left_post = (left_post - ball_location).normalize().flatten()
    ball_to_goal_right_post = (right_post -
                               ball_location).normalize().flatten()
    ball_to_goal_center = (utils.lerp(left_post, right_post, 0.5) -
                           ball_location).normalize().flatten()
    best_case = min(position_to_ball.dot(ball_to_goal_center),
                    position_to_ball.dot(ball_to_goal_right_post),
                    position_to_ball.dot(ball_to_goal_left_post))
    return best_case
Example #22
0
    def interpolate_value(self, values, phy_coord):
        '''
        get corresponding value given physical coordinate
        :param values: value field
        :param phy_coord:
        :return:
        '''

        # get coordinate in grid
        #TODO handle non-suqare cell
        grid_coord = phy_coord / self.cfg.dx - 0.5
        #TODO handle 3D input
        iu, iv = int(grid_coord[0]), int(grid_coord[1])
        # fract
        fu, fv = grid_coord[0] - iu, grid_coord[1] - iv
        #TODO test +0, +1
        a = self.sample(values, iu + 0.5, iv + 0.5)
        b = self.sample(values, iu + 1.5, iv + 0.5)
        c = self.sample(values, iu + 0.5, iv + 1.5)
        d = self.sample(values, iu + 1.5, iv + 1.5)

        return lerp(lerp(a, b, fu), lerp(c, d, fu), fv)
Example #23
0
def ramp(type, index, fromValue, toValue, duration):
    start = time.time()
    end = start + duration
    current = start

    while current <= end:
        s = (current - start) / duration
        t = max(0.0, min(s, 1.0))
        value = lerp(fromValue, toValue, t)
        send_message(controller, type, index, value)
        time.sleep(TICK)
        current = time.time()

    # make sure we end up exactly at our toValue
    send_message(controller, type, index, toValue)
Example #24
0
def zoom(cont):
    global zoom_level, target_altitude
    own = cont.owner
    #zoom_level = own["zoom_level"]
    
    mouse_w_up = own.sensors['MouseWUp']
    mouse_w_down = own.sensors['MouseWDown']
    
    if mouse_w_up.positive:
        zoom_level = clamp(zoom_level-1, 0, 7)
        target_altitude = zoom_to_altitude(zoom_level)
        
    elif mouse_w_down.positive:
        zoom_level = clamp(zoom_level+1, 0, 7)
        target_altitude = zoom_to_altitude(zoom_level)
        
    own.worldPosition.z = lerp(own.worldPosition.z, target_altitude, .1)
Example #25
0
	def split( self, numsplits ) :
		# check self has only one child
		children = self.getChildren()
		if( not children or len( children ) != 1 ) :
			utils.err( '%s does not have exactly ONE child. Skipping split...' % ( self.name() ) )
			return False
		child = children[0]

		# unparent child
		child.setParent( None )
		pm.select( None )

		# get position of self and child
		selfpos = self.getTranslation( space='world' )
		childpos = child.getTranslation( space='world' )
		# selfpos = pm.xform( self, q=True, translation=True, worldSpace=True )
		# childpos = pm.xform( child, q=True, translation=True, worldSpace=True )

		# first unparent self and store parent
		parent = self.getParent()
		self.setParent( None )

		# create joints by lerping between selfpos and childpos
		splitjoints = []
		lastjoint = self
		for i in range( 1, numsplits + 1 ) :
			t = i * ( 1.0 / ( numsplits + 1 ) )
			newjointpos = utils.lerp( selfpos, childpos, t )
			
			pm.select( None )
			newjoint = lastjoint.duplicate( n=utils.renumber_from_name( self.name(), i ), simple=True )
			newjoint.setTranslation( newjointpos, space='world' )
			
			splitjoints.append( newjoint )
			newjoint.setParent( lastjoint )
			lastjoint = newjoint
		child.setParent( lastjoint )

		self.setParent( parent )
		pm.select( self )
		return splitjoints
Example #26
0
    def generate_animation(self, name, frames, samples):
        frames_per_sample = frames // samples
        b = self.get_noise(self.batch_size)
        z1 = self.get_latent_inputs(self.batch_size)

        for i in range(samples):
            z2 = self.get_latent_inputs(self.batch_size)

            for j in range(frames_per_sample):
                # Linear interpolation of the two latent points
                z = lerp(z1, z2, j, frames_per_sample)
                Goz = self.G([z, b], training=False)
                # Frame number for putting animation together
                frame_no = i * frames_per_sample + j
                # Save the output for later processing (converting a batch of outputs directly to video can result in OOM)
                to_image(Goz[0]).save('./frames/frame' + str(frame_no) +
                                      '.jpg')

            z1 = z2

        to_video(name)
 def shrink(self, factor=2):
     alpha = 1.0 / (2 * factor)
     self.min = utils.lerp(alpha, self.min, self.max)
     self.max = utils.lerp(1.0 - alpha, self.min, self.max)
Example #28
0
#!/usr/bin/env python2

from PIL import Image
from utils import constrain, lerp, dist


if __name__ == "__main__":
    size = (128, 128)
    data = []

    for i in range(size[0]):
        for j in range(size[1]):
            x = lerp(-1.5, 1.5, float(i) / size[0])
            y = lerp(-1.5, 1.5, float(j) / size[1])

            pixel = 1.0 - dist(0.0, 0.0, x, y)

            data.append(int(constrain(pixel, 0.0, 1.0) * 255))

    light = Image.new('L', size)
    light.putdata(data)
    light.save("light.png", "PNG")
Example #29
0
#!/usr/bin/env python -B

import Image
from utils import lerp, sq, constrain


if __name__ == "__main__":
  D = 0.9
  size = (80, 80)
  data = []
  pal = []

  for i in range(8):
    pal.extend([0, 0, 0])
  for i in range(16):
    c = int(lerp(0, 255, float(i + 1) / 16))
    pal.extend([c, c, c])
  for i in range(4):
    pal.extend([255, 255, 255])
  for i in range(4):
    c = int(lerp(255, 0, float(i + 1) / 4))
    pal.extend([c, c, c])

  for i in range(size[0]):
    for j in range(size[1]):
      x = lerp(-D, D, float(i) / size[0])
      y = lerp(-D, D, float(j) / size[1])

      d = dist(x, y, 0, 0);

      if d < D:
Example #30
0
#!/usr/bin/env python -B

from PIL import Image
from utils import lerp, sq, constrain
from math import sqrt

if __name__ == "__main__":
    D = 0.9
    SIZE = 16
    data = []
    pal = []

    for i in range(8):
        c = int(lerp(0, 255, float(i) / 7))
        pal.extend([c, c, c])

    im = Image.new('L', (SIZE, SIZE * 8))
    im.putpalette(pal)
    pix = im.load()

    for size in range(8, 16):
        r = lerp(2.0, 1.0, float(size - 8) / 7)

        for i in range(SIZE):
            for j in range(SIZE):
                u = lerp(-r, r, float(i) / (SIZE - 1))
                v = lerp(-r, r, float(j) / (SIZE - 1))

                d = sq(1.4 - constrain(sqrt(sq(u) + sq(v)), 0.0, 1.4))

                pix[i, j + (size - 8) * SIZE] = int(constrain(d, 0.0, 1.0) * 7)
Example #31
0
from PIL import Image
from utils import dist, lerp, sq, constrain
import sys


if __name__ == "__main__":
    D = 0.9
    size = (80, 80)
    data = []
    pal = []

    for i in range(8):
        pal.extend([0, 0, 0])
    for i in range(16):
        c = int(lerp(0, 255, float(i + 1) / 16))
        pal.extend([c, c, c])
    for i in range(4):
        pal.extend([255, 255, 255])
    for i in range(4):
        c = int(lerp(255, 0, float(i + 1) / 4))
        pal.extend([c, c, c])

    for i in range(size[0]):
        for j in range(size[1]):
            x = lerp(-D, D, float(i) / size[0])
            y = lerp(-D, D, float(j) / size[1])

            d = dist(x, y, 0, 0)

            if d < D:
Example #32
0
#!/usr/bin/env python -B

import Image
from utils import lerp, sq, constrain, ccir601
from math import sqrt


def getcolors(im):
  pal = im.getpalette()
  return [(pal[i*3], pal[i*3+1], pal[i*3+2]) for _, i in im.getcolors()]

if __name__ == "__main__":
  im1 = Image.open('texture-16-1.png')
  im2 = Image.open('texture-16-2.png')

  pal1 = sorted(getcolors(im1), key=ccir601)
  pal2 = sorted(getcolors(im2), key=ccir601)

  im = Image.new('RGB', (16, 16))
  pix = im.load()

  for y in range(16):
    for x in range(16):
      r = lerp(pal1[x][0], pal2[x][0], float(y) / 15)
      g = lerp(pal1[x][1], pal2[x][1], float(y) / 15)
      b = lerp(pal1[x][2], pal2[x][2], float(y) / 15)

      pix[x, y] = (int(r), int(g), int(b))

  im.save('gradient.png', 'PNG')
Example #33
0
    return int(r * 64)


if __name__ == "__main__":
    width = 320
    height = 256
    A = 128
    B = 64
    pal = []

    for i in range(2):
        pal.extend([0, 0, 0])

    for i in range(6):
        c = int(lerp(0, 15, float(i) / 5))
        c = (c << 4) | c
        pal.extend([0, c, c])

    for i in range(6):
        c = int(lerp(15, 0, float(i) / 5))
        c = (c << 4) | c
        pal.extend([0, c, c])

    for i in range(2):
        pal.extend([0, 0, 0])

    im = Image.new('L', (width, height))
    im.putpalette(pal)
    pix = im.load()
Example #34
0
#!/usr/bin/env python3 -B

from PIL import Image
from utils import lerp, sq, constrain
from math import sqrt

if __name__ == "__main__":
    D = 0.9
    SIZE = 16
    data = []
    pal = []

    for i in range(8):
        c = int(lerp(0, 255, float(i) / 7))
        pal.extend([c, c, c])

    im = Image.new('L', (SIZE, SIZE * 8))
    im.putpalette(pal)
    pix = im.load()

    for size in range(8, 16):
        r = lerp(2.0, 1.0, float(size - 8) / 7)

        for i in range(SIZE):
            for j in range(SIZE):
                u = lerp(-r, r, float(i) / (SIZE - 1))
                v = lerp(-r, r, float(j) / (SIZE - 1))

                d = sq(1.4 - constrain(sqrt(sq(u) + sq(v)), 0.0, 1.4))

                pix[i, j + (size - 8) * SIZE] = int(constrain(d, 0.0, 1.0) * 7)
Example #35
0
    return int(r * 64)


if __name__ == "__main__":
    width = 320
    height = 256
    A = 128
    B = 64
    pal = []

    for i in range(2):
        pal.extend([0, 0, 0])

    for i in range(6):
        c = int(lerp(0, 15, float(i) / 5))
        c = (c << 4) | c
        pal.extend([0, c, c])

    for i in range(6):
        c = int(lerp(15, 0, float(i) / 5))
        c = (c << 4) | c
        pal.extend([0, c, c])

    for i in range(2):
        pal.extend([0, 0, 0])

    im = Image.new('L', (width, height))
    im.putpalette(pal)
    pix = im.load()
Example #36
0
 def happiness_freq(self):
     """Express happiness as a frequency value for animations."""
     return utils.lerp(self.happiness, -3.0, 3.0, 1.0/4.0, 2.0)
Example #37
0
 def lerp(lo, hi, step):
     r = lerp(lo.r, hi.r, step)
     g = lerp(lo.g, hi.g, step)
     b = lerp(lo.b, hi.b, step)
     return Color(r, g, b)
Example #38
0
    def get_wall_triangle_data(self, wall_index, bottom=None, top=None):
        """FBO data for the given wall. Includes, vertex, tex coords and
        lightmap tex coords.
        
        """
        # Vertex coordinates
        wall = self.walls[wall_index]
        left = wall[0]
        right = wall[1]
        if not bottom:
            bottom = self.floor_height
        if not top:
            top = self.ceiling_height
        
        # We'll use the top and bottom values to get scaled texture coordinates.
        room_height = self.ceiling_height - self.floor_height
        top_ratio = (top - self.floor_height) / room_height
        bottom_ratio = (bottom - self.floor_height) / room_height
        
        # Texture coordinates
        tex_wall = self.texture_walls[wall_index]
        tex_left = tex_wall[0]
        tex_right = tex_wall[1]
        tex_top = utils.lerp(self.wall_texture_floor_height,
                             self.wall_texture_ceiling_height, top_ratio)
        tex_bottom = utils.lerp(self.wall_texture_floor_height,
                                self.wall_texture_ceiling_height, bottom_ratio)
        
        # Lightmap tex coords
        lightmap_wall = self.lightmap_walls[wall_index]
        lightmap_left = lightmap_wall[0]
        lightmap_right = lightmap_wall[1]
        lightmap_top = utils.lerp(self.wall_lightmap_floor_height,
                                  self.wall_lightmap_ceiling_height, top_ratio)
        lightmap_bottom = utils.lerp(self.wall_lightmap_floor_height,
                             self.wall_lightmap_ceiling_height, bottom_ratio)

        data = []
        
        # Two triangles. First:
        data.extend((left[0], left[1], top))
        data.extend((tex_left, tex_top))
        data.extend((lightmap_left, lightmap_top))

        data.extend((right[0], right[1], top))
        data.extend((tex_right, tex_top))
        data.extend((lightmap_right, lightmap_top))
        
        data.extend((right[0], right[1], bottom))
        data.extend((tex_right, tex_bottom))
        data.extend((lightmap_right, lightmap_bottom))
        
        # Second
        data.extend((left[0], left[1], top))
        data.extend((tex_left, tex_top))
        data.extend((lightmap_left, lightmap_top))
        
        data.extend((right[0], right[1], bottom))
        data.extend((tex_right, tex_bottom))
        data.extend((lightmap_right, lightmap_bottom))

        data.extend((left[0], left[1], bottom))
        data.extend((tex_left, tex_bottom))
        data.extend((lightmap_left, lightmap_bottom))
        
        return data
Example #39
0
import Image
from utils import lerp, sq, constrain, ccir601
from math import sqrt


def getcolors(im):
    pal = im.getpalette()
    return [(pal[i * 3], pal[i * 3 + 1], pal[i * 3 + 2])
            for _, i in im.getcolors()]


if __name__ == "__main__":
    im1 = Image.open('texture-16-1.png')
    im2 = Image.open('texture-16-2.png')

    pal1 = sorted(getcolors(im1), key=ccir601)
    pal2 = sorted(getcolors(im2), key=ccir601)

    im = Image.new('RGB', (16, 16))
    pix = im.load()

    for y in range(16):
        for x in range(16):
            r = lerp(pal1[x][0], pal2[x][0], float(y) / 15)
            g = lerp(pal1[x][1], pal2[x][1], float(y) / 15)
            b = lerp(pal1[x][2], pal2[x][2], float(y) / 15)

            pix[x, y] = (int(r), int(g), int(b))

    im.save('gradient.png', 'PNG')
Example #40
0
import Image
from utils import lerp


if __name__ == "__main__":
  width = 320
  height = 256
  A = 128
  B = 64
  pal = []

  for i in range(2):
    pal.extend([0, 0, 0])

  for i in range(6):
    c = int(lerp(0, 15, float(i) / 5))
    c = (c << 4) | c
    pal.extend([0, c, c])

  for i in range(6):
    c = int(lerp(15, 0, float(i) / 5))
    c = (c << 4) | c
    pal.extend([0, c, c])

  for i in range(2):
    pal.extend([0, 0, 0])

  im = Image.new('L', (width, height))
  im.putpalette(pal)
  pix = im.load()
Example #41
0
from PIL import Image
from utils import lerp

if __name__ == "__main__":
    width = 320
    height = 256
    A = 128
    B = 64
    pal = []

    for i in range(2):
        pal.extend([0, 0, 0])

    for i in range(6):
        c = int(lerp(0, 15, float(i) / 5))
        c = (c << 4) | c
        pal.extend([0, c, c])

    for i in range(6):
        c = int(lerp(15, 0, float(i) / 5))
        c = (c << 4) | c
        pal.extend([0, c, c])

    for i in range(2):
        pal.extend([0, 0, 0])

    im = Image.new('L', (width, height))
    im.putpalette(pal)
    pix = im.load()
Example #42
0
#!/usr/bin/env python -B

import Image
from utils import constrain, lerp, dist


if __name__ == "__main__":
  size = (256, 256)
  data = []

  for i in range(size[0]):
    for j in range(size[1]):
      x = lerp(-2.0, 2.0, float(i) / size[0])
      y = lerp(-2.0, 2.0, float(j) / size[1])

      pixel = 1.0 - dist(0.0, 0.0, x, y)

      data.append(int(constrain(pixel, 0.0, 1.0) * 255))

  light = Image.new('L', size)
  light.putdata(data)
  light.save("data/light.tga", "TGA")
Example #43
0
 def brightness_hsv(self):
     """Express brightness as a HSV value (0 to 1.0)."""
     return utils.lerp(self.brightness, 0.0, 3.0, 0.0, 1.0)
Example #44
0
 def generate(self, fn, view):
     for j in range(self.height):
         for i in range(self.width):
             x = lerp(view[0], view[1], float(i) / self.width)
             y = lerp(view[2], view[3], float(j) / self.height)
             self.put(i, j, fn(x, y))
Example #45
-1
 def lerp(lo, hi, step):
     r = lerp(lo.r, hi.r, step)
     g = lerp(lo.g, hi.g, step)
     b = lerp(lo.b, hi.b, step)
     return Color(r, g, b)