-- posted 23 April 2007 by Duoas
Description
A simple class that produces vectors interpolating between two given vectors in a given amount of time. The vectors may be any dimention, so long as they can be parsed as a sequence. The interpolation defaults to a linear interpolation, but two parameters are provided to modify it into various smooth interpolations.
Background
I had been playing around with the [[LinearInterpolator]] and [[SmoothInterpolator]] functions here in the cookbook, and after fixing a couple (serious) bugs, I made some other heavy modifications to suit my needs. Finally, I decided to post my updates.
I don't have Numeric, and as it is getting rather old anyway I have puttered along without it. You might find some speed improvements by changing the list comprehensions into Numeric.arrays. The following apply:
Well, you get the idea.
interpolator.py
This is the module. You can run it through
R"""
interpolator.py
Perform a simple interpolation between two points of any dimention, without
the use of Numeric.
2007 Michael Thomas Greer
Released to the Public Domain
"""
class Interpolator( object ):
R"""
The line actor. Returns successive points along a line until completely
traversed. Once traversed this class can do nothing more.
Care has been taken to fix errors due to floating-point arithmetic.
implementation notes
Following the docs, some simple math must be done to get the movement
desired. The first thing to remember is that we cannot change the FPS,
which is to say, we cannot change the speed of the program. So all our
manipulations work by modifying the step size between the start and
stop vectors (which, in other words, is the apparent speed of line
traversal).
For the default linear interpolation, the step size remains constant:
step = dx *( 1.0 /FPS ) /seconds
where dx represents the total distance to traverse for each dimention.
For non-linear interpolations, we must factor in our shape, which is
specified relative to the linear interpolation speed. The shape is a
simple power function which gives us a nice, spikey curve with a
vertical asymptote at the midpoint. The function is:
factor = shape *(closeness_to_asymptote **(shape -1.0))
where closeness_to_asymptote is a number in the range [0.0, 1.0]; 0.0
being at either end of the line and 1.0 being at the asymptote. (The
location of the asymptote, or "middle", is modifiable.)
The final calculation is to modify each vector position by (step *factor).
"""
#---------------------------------------------------------------------------
def __init__(
self,
start = None,
stop = None,
seconds = None,
fps = None,
shape = 1.0,
middle = 0.5
):
R"""
Create a new interpolator to produce timed vectors along a line.
arguments
start - The initial vector. If no vectors are specified the object is
treated as a placeholder object and does absolutely nothing
but return the two-dimentional vector (0, 0).
stop - The final vector. If no final vector is specified the object
is treated as a placeholder object and does absolutely nothing
but return the 'start' vector.
seconds - The number of seconds you wish the interpolation to take.
fps - The current number of frames per second. If you specify
seconds you must specify the FPS, otherwise a ValueError
exception is raised with the message "You must specify both
'seconds' and 'fps'."
shape - Modify the interpolation as non-linear.
First some quick information to explain:
- The total time to traverse the line is constant (in other
words, this function cannot take more or less 'seconds'
worth of vectors than you specify).
- For the same reason, the number of vectors produced by this
function (for a given value of 'seconds') is constant.
- Hence, the -speed- of a vector is defined wholly by the
distance between it the previously produced vector.
- In a linear interpolation, the distance between vectors (or
again, the speed of each vector) is constant; every vector
has the same speed.
- In a shaped interpolation, the speed of individual vectors
is modified: some are faster and some are slower.
The shape is the number of times greater than linear speed the
middle vector travels.
A shape of 1.0 is a linear interpolation. A shape of 2.0 has
slower vectors at the end and a vector in the middle traveling
twice as fast as it would in a linear interpolation. A shape
of 0.5 travels half as fast. There really isn't any upper-
limit, but zero is the lower. You'll get a ValueError if you
try any value less-than or equal-to zero.
middle - The location of the "middle vector" along the line, expressed
as a value from 0.0 (at 'start') to 1.0 (at 'stop').
"""
self._sec = -1
self._length = 0
if start is None: start = (0, 0)
if stop is None: self.stop = start
else:
if (seconds is None) or (fps is None):
raise ValueError( "You must specify both 'seconds' and 'fps'" )
if shape <= 0.0:
raise ValueError( "The 'shape' argument must have value > 0.0" )
if not (0.0 <= middle <= 1.0):
raise ValueError( "The 'middle' argument must be in range [0.0, 1.0]" )
self.stop = stop
self.diff = [ b -a for a, b in zip( start, stop ) ]
self.inc = 1.0 / fps
self.step = [ a *self.inc /seconds for a in self.diff ]
self._pos = start
self._sec = seconds
self.seconds = seconds
self.shape = shape
self.mid = middle
self.maxs = [ max( a, b ) for a, b in zip( start, stop ) ]
self.mins = [ min( a, b ) for a, b in zip( start, stop ) ]
self._length = None
#---------------------------------------------------------------------------
def next( self ):
R"""
Calculate the location of the next vector in the line.
The 'start' vector cannot be a "next" vector. (This is actually rather
convenient if you think about it.) That said, if your interpolation is set
up right, the first "next" vector might actually be in the same location
as the 'start' vector...
Care is taken that the 'stop' vector is always the final vector.
returns
The next vector or None if all done.
"""
def d( a, b, c ):
if b == 0.0: return c
else: return a /b
if self._sec >= 0.0:
if self.shape == 1.0: factor = 1.0
else:
percent = 1.0 -(self._sec /self.seconds) # percent complete
if percent < 0.95:
if percent > self.mid: k = d( (1.0 -percent), (1.0 -self.mid), 1.0 )
else: k = d( percent, self.mid, 0.0 )
if k in [0.0, 1.0]: factor = k *self.shape
else: factor = pow( k, self.shape -1.0 ) *self.shape
else:
# The final 5% of the line is calculated linearly to avoid any
# 'jump' or 'snap' artifacts caused by FPU arithmetic errors.
if self.mid is not None:
self.diff = [ b -a for a, b in zip( self._pos, self.stop ) ]
self.step = [ a *self.inc /self._sec for a in self.diff ]
self.mid = None
factor = 1.0
self._pos = tuple(
[ min( max(
a +(step *factor),
mina ), maxa )
for a, step, mina, maxa in
zip( self._pos, self.step, self.mins, self.maxs )
]
)
self._sec -= self.inc
return self._pos
else:
self._pos = self.stop
return None
#---------------------------------------------------------------------------
def _get_pos( self ):
R"""Return the current vector's location."""
return self._pos
#---------------------------------------------------------------------------
def _get_length( self ):
R"""
Returns the length of the line. The line's length is not calculated
until first required.
"""
from math import sqrt
if self._length is None:
sum = 0
for a in self.diff: sum += a *a
self._length = sqrt( sum )
return self._length
#---------------------------------------------------------------------------
pos = property( _get_pos, doc='The location of the current vector. Read-only.' )
length = property( _get_length, doc='The length of the line. Read-only.' )
# end interpolator
test.py
Here is a simple test program you can use to play around with it.
Click anywhere on the display to cause the colored squares to re-center themselves around the spot where you clicked, using a one-and-a-half-second interpolation.
Enjoy playing with it!
import pygame
from interpolator import *
RESOLUTION = (800, 600) # (adjust for your resolution)
SECONDS = 1.5 # slow enough to see how it goes, but not too slow...
class Sprite( pygame.sprite.Sprite ):
def __init__( self, color, pos ):
pygame.sprite.Sprite.__init__( self )
self.image = pygame.Surface( (30, 30) )
self.image.fill( color )
self.rect = self.image.get_rect()
self.rect.center = pos
self.line = Interpolator( pos )
def update( self, screen ):
screen.fill( (0, 0, 0), self.rect )
self.line.next()
self.rect.center = self.line.pos
screen.blit( self.image, self.rect )
def main():
pygame.init()
screen = pygame.display.set_mode( RESOLUTION )
x, y = RESOLUTION
x //= 2
y //= 2
shapes = [1.0, 2.0, 2.0, 4.0, 0.5]
middles = [0.5, 0.5, 1.0, 0.0, 0.5]
xoffsets = [0, -30, 30, -30, 30]
yoffsets = [0, -30, -30, 30, 30]
colors = [
( 52, 98, 166),
(244, 127, 48),
(176, 84, 175),
(229, 35, 58),
(255, 255, 162)
]
all = pygame.sprite.OrderedUpdates()
for xoffset, yoffset, color in zip( xoffsets, yoffsets, colors ):
all.add( Sprite( color, (x +xoffset, y +yoffset) ) )
clock = pygame.time.Clock()
all.update( screen )
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type in [pygame.QUIT, pygame.KEYDOWN]:
return
elif event.type == pygame.MOUSEBUTTONDOWN:
fps = clock.get_fps()
x, y = event.pos
for sprite, shape, middle, xoffset, yoffset in zip(
all.sprites(), shapes, middles, xoffsets, yoffsets
):
sprite.line = Interpolator(
sprite.rect.center,
(x +xoffset, y +yoffset),
SECONDS,
fps,
shape,
middle
)
all.update( screen )
pygame.display.update()
clock.tick( 200 )
main()
JAPANESE PATTERN-DESIGNER. JAPANESE PATTERN-DESIGNER. All that warm afternoon we paid the tiresome penalty of having pushed our animals too smartly at the outset. We grew sedate; sedate were the brows of the few strangers we met. We talked in pairs. When I spoke with Miss Harper the four listened. She asked about the evils of camp life; for she was one of that fine sort to whom righteousness seems every man's and woman's daily business, one of the most practical items in the world's affairs. And I said camp life was fearfully corrupting; that the merest boys cursed and swore and stole, or else were scorned as weaklings. Then I grew meekly silent and we talked in pairs again, and because I yearned to talk most with Camille I talked most with Estelle. Three times when I turned abruptly from her to Camille and called, "Hark!" the fagged-out horses halted, and as we struck our listening pose the bugle's faint sigh ever farther in our rear was but feebly proportioned to the amount of our gazing into each other's eyes. "I'm glad you didn't," Bruce smiled. "What a sensation those good people will have presently! And most of them have been on intimate terms with our Countess. My darling, I shall never be easy in my mind till you are out of that house." Those manifestations of sympathy which are often so much more precious than material assistance were also repugnant to Stoic principles. On this subject, Epict¨ºtus expresses himself with singular harshness. ¡®Do not,¡¯ he says, ¡®let yourself be put out by the sufferings of your friends. If they are unhappy, it is their own fault. God made them for happiness, not for misery. They are grieved at parting from you, are they? Why, then, did they set their affections on things outside themselves? If they suffer for their folly it serves them right.¡¯93 You are awfully good, Daddy, to bother yourself with me, when you're ¡°Some strong, pungent liquid had been poured on the green necklace,¡± the letter from the millionaire stated. ¡°No alarm was given. My wife did not want to broadcast either the fact that she had the real gems or the trouble in the hotel. But people had heard the ¡®fire!¡¯ cry and doubtless some suspected the possible truth, knowing why she was getting ready. ¡°But the switches that control the motor for the drum are right out on the wall in plain sight,¡± he told himself, moving over toward them, since the rolling door was left wide open when the amphibian was taken out. ¡°Yes, here they all are¡ªthis one up for lifting the door, and down to drop it. And that switch was in the neutral¡ª¡®off¡¯¡ªposition when we were first here¡ªand it¡¯s in neutral now.¡± The strong sense, lively fancy, and smart style of his satires, distinguished also Pope's prose, as in his "Treatise of the Bathos; or, the Art of Sinking in Poetry;" his "Memoirs of P. P., Clerk of this Parish"¡ªin ridicule of Burnet's "Own Times"¡ªhis Letters, etc. In some of the last he describes the country and country seats, and the life there of his friends; which shows that, in an age more percipient of the charm of such things, he would have probably approached nearer to the heart of Nature, and given us something more genial and delightful than anything that he has left us. The taste for Italian music was now every day increasing; singers of that nation appeared with great applause at most concerts. In 1703 Italian music was introduced into the theatres as intermezzi, or interludes, consisting of singing and dancing; then whole operas appeared, the music Italian, the words English; and, in 1707, Urbani, a male soprano, and two Italian women, sang their parts all in Italian, the other performers using English. Finally, in 1710, a complete Italian opera was performed at the Queen's Theatre, Haymarket, and from that time the Italian opera was regularly established in London. This led to the arrival of the greatest composer whom the world had yet seen. George Frederick Handel was born at Halle, in Germany, in 1685. He had displayed wonderful genius for music as a mere child, and having, at the age of seven years, astonished the Duke of Saxe Weissenfels¡ªat whose court his brother-in-law was a valet¡ªwho found him playing the organ in the chapel, he was, by the Duke's recommendation, regularly educated for the profession of music. At the age of ten, Handel composed the church service for voices and instruments; and after acquiring a great reputation in Hamburg¡ªwhere, in 1705, he brought out his "Almira"¡ªhe proceeded to Florence, where he produced the opera of "Rodrigo," and thence to Venice, Rome, and Naples. After remaining in Italy four years, he was induced to come to England in 1710, at the pressing entreaties of many of the English nobility, to superintend the opera. But, though he was enthusiastically received, the party spirit which raged at that period soon made it impossible to conduct the opera with any degree of self-respect and independence. He therefore abandoned the attempt, having sunk nearly all his fortune in it, and commenced the composition of his noble oratorios. Racine's "Esther," abridged and altered by Humphreys, was set by him, in 1720, for the chapel of the Duke of Chandos at Cannons. It was, however, only by slow degrees that the wonderful genius of Handel was appreciated, yet it won its way against all prejudices and difficulties. In 1731 his "Esther" was performed by the children of the chapel-royal at the house of Bernard Gates, their master, and the following year, at the king's command, at the royal theatre in the Haymarket. It was fortunate for Handel that the monarch was German too, or he might have quitted the country in disgust before his fame had triumphed over faction and ignorance. So far did these operate, that in 1742, when he produced his glorious "Messiah," it was so coldly received that it was treated as a failure. Handel, in deep discouragement, however, gave it another trial in Dublin, where the warm imaginations of the Irish caught all its sublimity, and gave it an enthusiastic reception. On its next presentation in London his audience reversed the former judgment, and the delighted composer then presented the manuscript to the Foundling Hospital, where it was performed annually for the benefit of that excellent institution, and added to its funds ten thousand three hundred pounds. It became the custom, from 1737, to perform oratorios[156] on the Wednesdays and Fridays in Lent. Handel, whose genius has never been surpassed for vigour, spirit, invention, and sublimity, became blind in his latter years. He continued to perform in public, and to compose, till within a week of his death, which took place on April 13, 1759. The Deacon took his position behind a big black walnut, while he reconnoitered the situation, and got his bearings on the clump of willows. He felt surer than ever of his man, for he actually saw a puff of smoke come from it, and saw that right behind the puff stood a willow that had grown to the proportions of a small tree, and had its bark rubbed off by the chafing of driftwood against it. "Certainly. I see it very plainly," said the Surgeon, after looking them over. "Very absurd to start such a report, but we are quite nervous on the subject of smallpox getting down to the army. "Yes, just one." Reuben pulled up his chair to the table. His father sat at one end, and at the other sat Mrs. Backfield; Harry was opposite Reuben. Reuben counted them¡ªten. Then he pushed them aside, and began rummaging in the cart among cabbages and bags of apples. In a second or two he had dragged out five more rabbits. Robert stood with hanging head, flushed cheeks, and quivering hands, till his father fulfilled his expectations by knocking him down. HoMEBT ÏÂÔØ ÀïÃÀÓÈÀûæ«
ENTER NUMBET 0016www.kwdzrn.com.cn