Added the trunk/branches/tags directories at repository root, and moved previous root into trunk/

git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1002 4e206d99-4929-0410-ac5d-dfc041789085
This commit is contained in:
laurentgom 2009-01-28 16:18:34 +00:00
commit 2f524481c1
974 changed files with 295448 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 868 B

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

166
python/samples/opengl.py Normal file
View file

@ -0,0 +1,166 @@
#!/usr/bin/python
from PySFML import *
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
def main():
# Create main window
App = sf.RenderWindow(sf.VideoMode(800, 600), "SFML OpenGL")
App.PreserveOpenGLStates(True)
# Create a sprite for the background
BackgroundImage = sf.Image()
if not BackgroundImage.LoadFromFile("../../samples/bin/datas/opengl/background.jpg"):
return
Background = sf.Sprite(BackgroundImage)
# Load an OpenGL texture.
# We could directly use a sf.Image as an OpenGL texture (with its Bind() member function),
# but here we want more control on it (generate mipmaps, ...) so we create a new one
Image = sf.Image()
if not Image.LoadFromFile("../../samples/bin/datas/opengl/texture.jpg"):
return
# The next line is a bit different from the C++ version
Texture = glGenTextures(1) # instead of glGenTextures(1, &Texture);
glBindTexture(GL_TEXTURE_2D, Texture)
# It is almost the same line there, except in C++, the last argument was Image.GetPixelsPtr().
# With GetPixelsPtr, PySFML returns a PyCObject: "an opaque value, useful for C extension
# modules who need to pass an opaque value (as a void* pointer) through Python code to other C code".
# However, gluBuild2DMipmaps' python version takes a string as last argument (which is normally a
# pointer to pixels data). This is why Image.GetPixelsPtr is replaced by Image.GetPixelsString.
# This function (that doesn't exist in C++ SFML) returns a string that contains the pixels data.
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Image.GetWidth(), Image.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, Image.GetPixels())
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
# Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST)
glDepthMask(GL_TRUE)
glClearDepth(1.)
# Setup a perspective projection
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(90., 1., 1., 500.)
# Bind our texture
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, Texture)
glColor4f(1., 1., 1., 1.)
# Create a clock for measuring the time elapsed
Clock = sf.Clock()
# Start game loop
while App.IsOpened():
# Process events
Event = sf.Event()
while App.GetEvent(Event):
# Close window : exit
if Event.Type == sf.Event.Closed:
App.Close()
# Escape key : exit
if (Event.Type == sf.Event.KeyPressed) and (Event.Key.Code == sf.Key.Escape):
App.Close()
# Adjust the viewport when the window is resized
if Event.Type == sf.Event.Resized:
glViewport(0, 0, Event.Size.Width, Event.Size.Height);
# Draw background
App.Draw(Background)
# Clear depth buffer
glClear(GL_DEPTH_BUFFER_BIT)
# Apply some transf.ormations
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0, 0, -200)
glRotatef(Clock.GetElapsedTime() * 50, 1, 0, 0)
glRotatef(Clock.GetElapsedTime() * 30, 0, 1, 0)
glRotatef(Clock.GetElapsedTime() * 90, 0, 0, 1)
# Draw a cube
glBegin(GL_QUADS)
glTexCoord2f(0, 0)
glVertex3f(-50., -50., -50.)
glTexCoord2f(0, 1)
glVertex3f(-50., 50., -50.)
glTexCoord2f(1, 1)
glVertex3f( 50., 50., -50.)
glTexCoord2f(1, 0)
glVertex3f( 50., -50., -50.)
glTexCoord2f(0, 0)
glVertex3f(-50., -50., 50.)
glTexCoord2f(0, 1)
glVertex3f(-50., 50., 50.)
glTexCoord2f(1, 1)
glVertex3f( 50., 50., 50.)
glTexCoord2f(1, 0)
glVertex3f( 50., -50., 50.)
glTexCoord2f(0, 0)
glVertex3f(-50., -50., -50.)
glTexCoord2f(0, 1)
glVertex3f(-50., 50., -50.)
glTexCoord2f(1, 1)
glVertex3f(-50., 50., 50.)
glTexCoord2f(1, 0)
glVertex3f(-50., -50., 50.)
glTexCoord2f(0, 0)
glVertex3f(50., -50., -50.)
glTexCoord2f(0, 1)
glVertex3f(50., 50., -50.)
glTexCoord2f(1, 1)
glVertex3f(50., 50., 50.)
glTexCoord2f(1, 0)
glVertex3f(50., -50., 50.)
glTexCoord2f(0, 1)
glVertex3f(-50., -50., 50.)
glTexCoord2f(0, 0)
glVertex3f(-50., -50., -50.)
glTexCoord2f(1, 0)
glVertex3f( 50., -50., -50.)
glTexCoord2f(1, 1)
glVertex3f( 50., -50., 50.)
glTexCoord2f(0, 1)
glVertex3f(-50., 50., 50.)
glTexCoord2f(0, 0)
glVertex3f(-50., 50., -50.)
glTexCoord2f(1, 0)
glVertex3f( 50., 50., -50.)
glTexCoord2f(1, 1)
glVertex3f( 50., 50., 50.)
glEnd()
# Draw some text on top of our OpenGL object
Text = sf.String("This is a rotating cube")
Text.SetPosition(230., 300.)
Text.SetColor(sf.Color(128, 0, 128))
App.Draw(Text)
# Finally, display the rendered frame on screen
App.Display()
# Don't forget to destroy our texture
# In C++, the call to this function was a bit different
glDeleteTextures(Texture) # instead of glDeleteTextures(1, &Texture);
return
main()

43
python/samples/sound.py Normal file
View file

@ -0,0 +1,43 @@
#!/usr/bin/python
# You can notice that here we use PySFML.sf instead of just PySFML
# Therefore it won't be needed to put sf. in front of SFML classes
from PySFML.sf import *
def Main():
Buffer = SoundBuffer()
if not Buffer.LoadFromFile("data/fart.wav"): # Loads the sound
return
Fart = Sound(Buffer, False)
WindowWidth, WindowHeight = 640, 480
App = RenderWindow(VideoMode(WindowWidth,WindowHeight,32), "Sound with PySFML", Style.Close, WindowSettings(24,8,0))
App.SetFramerateLimit(30)
EventHandler = Event()
InputHandler = App.GetInput()
Text = String("Turn the sound on.\nClick anywhere on the screen.\nMove the mouse. Click again.\nTry clicking in the corners.")
Text.SetX(30.)
Text.SetY(20.)
Text.SetColor(Color(150, 100, 10, 255))
while App.IsOpened(): # Main loop
while App.GetEvent(EventHandler): # Event Handler
if EventHandler.Type == Event.Closed:
App.Close()
if EventHandler.Type == Event.KeyPressed and EventHandler.Key.Code == Key.Escape:
App.Close()
if EventHandler.Type == Event.MouseButtonPressed and EventHandler.MouseButton.Button == Mouse.Left:
Fart.SetPitch(1.5 - 1.*InputHandler.GetMouseY()/WindowHeight)
Fart.SetPosition( 1.*(InputHandler.GetMouseX() - WindowWidth/2)/(WindowWidth/20), 2., -2.)
Fart.Play()
App.Draw(Text)
App.Display()
App.Clear(Color.Black)
Main()

View file

@ -0,0 +1,68 @@
#!/usr/bin/env python
from PySFML import *
def Main():
# Check that the device can capture audio
if sf.SoundRecorder.CanCapture() == False:
print "Sorry, audio capture is not supported by your system"
return
# Choose the sample rate
SampleRate = 0
SampleRate = int(raw_input("Please choose the sample rate for sound capture (44100 is CD quality) : "))
# Wait for user input...
print "Press enter to start recording audio"
raw_input()
# Here we'll use an integrated custom recorder, which saves the captured data into a sfSoundBuffer
Recorder = sf.SoundBufferRecorder()
# Audio capture is done in a separate thread, so we can block the main thread while it is capturing
Recorder.Start(SampleRate)
print "Recording... press enter to stop"
raw_input()
Recorder.Stop()
# Get the buffer containing the captured data
Buffer = Recorder.GetBuffer()
# Display captured sound informations
print "Sound information :"
print " " + str(Buffer.GetDuration()) + " seconds"
print " " + str(Buffer.GetSampleRate()) + " samples / seconds"
print " " + str(Buffer.GetChannelsCount()) + " channels"
# Choose what to do with the recorded sound data
Choice = str(raw_input("What do you want to do with captured sound (p = play, s = save) ? "))
if Choice == 's':
# Choose the filename
Filename = str(raw_input("Choose the file to create : "))
# Save the buffer
Buffer.SaveToFile(Filename);
else:
# Create a sound instance and play it
Sound = sf.Sound(Buffer)
Sound.Play()
# Wait until finished
while Sound.GetStatus() == sf.Sound.Playing:
# Display the playing position - I don't know how to do this in python
# std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << Sound.GetPlayingOffset() << " sec";
# Leave some CPU time for other threads
sf.Sleep(0.1)
# Finished !
print "Done !"
# Wait until the user presses 'enter' key
print "Press enter to exit..."
raw_input()
return
Main()

49
python/samples/sound_stream.py Executable file
View file

@ -0,0 +1,49 @@
#!/usr/bin/python
from PySFML import sf
class MyCustomStream(sf.SoundStream):
def Open(self, Filename):
# Load the sound data into a sound buffer
self.SoundData = sf.SoundBuffer()
if not self.SoundData.LoadFromFile(Filename):
return False
# Initialize the stream with the sound parameters
self.Initialize(self.SoundData.GetChannelsCount(), self.SoundData.GetSampleRate())
# Copy the audio samples into our internal array
self.myBuffer = self.SoundData.GetSamples()
return True
def OnStart(self):
self.myOffset = 0
self.myBufferSize = 80000
return True
def OnGetData(self):
# Check if there is enough data to stream
if self.myOffset > len(self.myBuffer):
# Returning something else than a string means that we want to stop playing the stream
return False
# Data contains the string of samples we will return
if self.myOffset + self.myBufferSize >= len(self.myBuffer):
print "End of audio data reached"
Data = self.myBuffer[self.myOffset:]
else:
Data = self.myBuffer[self.myOffset:self.myOffset+self.myBufferSize]
# Update the offset
self.myOffset = self.myBufferSize + self.myOffset
return Data
def Main():
Stream = MyCustomStream()
Stream.Open("./data/fart.wav")
Stream.Play()
print "Playing 5 seconds of audio data..."
sf.Sleep(5)
Stream.Stop()
print "Press enter to exit..."
raw_input()
Main()

240
python/samples/worm.py Normal file
View file

@ -0,0 +1,240 @@
#!/usr/bin/python
from PySFML import *
import math
import random
import sys
def Game(Difficulty):
PartsPerFrame = 1 + Difficulty # Number of drawn base parts each frame
PartsSpacing = 3 # Each worm's base part is separated by PartsSpacing pixels
TurnStep = 0.15 # Turn the worm's head of 0.15 rad
PartSize = 6.0 # worm's base part size for collision
PartRealSize = 18.0 # worm's real base part size for drawing
# Load images
Rond = sf.Image() # Image containing the base part of the worm
if not Rond.LoadFromFile("./data/rond2.png"):
print "Could not load data/rond2.png"
return
WormPart = sf.Sprite(Rond)
WormPart.SetCenter(Rond.GetWidth()/2, Rond.GetHeight()/2)
AppleImg = sf.Image() # Apple's image
if not AppleImg.LoadFromFile("./data/apple.png"):
print "Could not load data/apple.png"
return
Apple = sf.Sprite(AppleImg, 0, 0, 1, 1, 0) # Corresponding sprite
Black = sf.Color(0,0,0,255)
UglyYellow = sf.Color(220, 220, 20, 255)
Stop = False
Event = sf.Event() # Our events manager
Level = 0
ShrinkValue = 20
Border = 30
ArenaTop = 20
ArenaBottom = 520
RequiredLength = 300
ExitLeft = 350
ExitRight = 450
ExitImg = sf.Image(ExitRight-ExitLeft, ArenaTop, Black)
Exit = sf.Sprite(ExitImg, ExitLeft, 0, 1, 1, 0)
Score = 0
HeadX, HeadY = 0, 0
while not Stop:
#Initialize a new game
Level += 1
ArenaLeft = ShrinkValue*Level
ArenaRight = 800-ShrinkValue*Level
ArenaImg = sf.Image(ArenaRight-ArenaLeft, ArenaBottom-ArenaTop, Black)
Arena = sf.Sprite(ArenaImg, ArenaLeft, ArenaTop, 1, 1, 0)
AppleX, AppleY = random.randrange(ArenaLeft+Border, ArenaRight-Border), random.randrange(ArenaTop+Border, ArenaBottom-Border)
Apple.SetX(AppleX - AppleImg.GetWidth()/2) # We move the apple to somewhere else, randomly
Apple.SetY(AppleY - AppleImg.GetHeight()/2)
Crash = False
Running = True
LevelStr = sf.String("Level: " + str(Level))
LevelStr.SetPosition(60., 540.)
LevelStr.SetColor(UglyYellow)
ScoreStr = sf.String("Score: 0")
ScoreStr.SetPosition(260., 540.)
ScoreStr.SetColor(UglyYellow)
Length = 1
TargetedLength = 30
Worm = [[ArenaLeft+50., ArenaTop+50.]]
Angle = 0
i = 0
Dir = 0
while Running: # Game main loop
while App.GetEvent(Event): # Event Handler
if Event.Type == sf.Event.Closed:
App.Close()
return
if Event.Type == sf.Event.KeyPressed:
if Event.Key.Code == sf.Key.Escape:
Running = False
Stop = True
if Event.Key.Code == sf.Key.Left:
Dir = -1
if Event.Key.Code == sf.Key.Right:
Dir = 1
if Crash and Length<=1:
Running = False
if Event.Type == sf.Event.KeyReleased:
if Event.Key.Code == sf.Key.Left and Dir == -1:
Dir = 0
if Event.Key.Code == sf.Key.Right and Dir == 1:
Dir = 0
App.Draw(Arena)
if not Crash: # Create new parts and check collisions if the worm hasn't crashed yet
for i in range(0, PartsPerFrame): # We create PartsPerFrame Worm's parts
Angle += Dir*TurnStep
HeadX, HeadY = Worm[Length-1][0]+PartsSpacing*math.cos(Angle), Worm[Length-1][1]+PartsSpacing*math.sin(Angle)
if TargetedLength <= RequiredLength:
if math.sqrt ( (AppleX - HeadX)**2 + (AppleY - HeadY)**2 ) < 14 + PartSize/2: # The Worm ate the apple
Score += 1
TargetedLength += 20 # The worm gets longer
if TargetedLength <= RequiredLength:
AppleX, AppleY = random.randrange(ArenaLeft+Border, ArenaRight-Border), random.randrange(ArenaTop+Border, ArenaBottom-Border)
Apple.SetX(AppleX - AppleImg.GetWidth()/2) # We move the apple to somewhere else, randomly
Apple.SetY(AppleY - AppleImg.GetHeight()/2)
App.Draw(Apple)
if HeadX<ArenaLeft+PartSize/2 or HeadX>ArenaRight-PartSize/2 or HeadY<ArenaTop+PartSize/2 or HeadY>ArenaBottom-PartSize/2: # Crash into a wall
if Length > RequiredLength:
if HeadY<ArenaTop+PartSize/2:
if HeadX<ExitLeft+PartSize/2 or HeadX>ExitRight-PartSize/2:
Crash = True
elif HeadY < 0:
Length = 0
Running = False # Level completed!
else:
Crash = True
elif Running:
Crash = True
if not Crash:
Worm.append([HeadX, HeadY])
Length += 1
if TargetedLength > RequiredLength:
App.Draw(Exit)
if Length >= TargetedLength:
Worm[0:TargetedLength] = Worm[Length-TargetedLength:Length]
for i in range(Length, TargetedLength):
del Worm[i]
Worm[TargetedLength:Length] = []
Length = TargetedLength
for i in range(0, Length):
WormPart.SetPosition(Worm[i][0], Worm[i][1])
App.Draw(WormPart) # Draw the part on screen
if i < Length - PartSize/PartsSpacing - 1:
if math.sqrt( (HeadX-Worm[i][0])**2 + (HeadY-Worm[i][1])**2 ) < PartSize and Running: # Check for collision
Crash = True
if Crash and Length>0:
TargetedLength -= PartsPerFrame
ScoreStr.SetText("Score: " + str(Score))
App.Draw(ScoreStr)
App.Draw(LevelStr)
App.Display() # Refresh Screen
App.Clear(BGColor)
# End of the game
if Crash:
Level = 0
Score = 0
else:
Score += 5 # End level bonus
del Worm
del Arena
del ArenaImg
def Menu():
Selection = 0
TextColor = sf.Color(220, 220, 20, 255)
Running = True
Event = sf.Event()
Title = sf.String("PyWorm!")
Title.SetX(320.)
Title.SetY(50.)
Title.SetColor(TextColor)
Levels = ["Very Easy", "Easy", "Medium", "Hard"]
Xs = [320., 350., 330., 350.]
Strings = [0,0,0,0]
for i in range(0, 4):
Strings[i] = sf.String(Levels[i])
Strings[i].SetColor(TextColor)
Strings[i].SetPosition(Xs[i], 200. + 80*i)
RectangleImg = sf.Image(ScreenWidth, 40, sf.Color(50,50,10,255))
Rectangle = sf.Sprite(RectangleImg, 0, 350, 1, 1, 0)
while App.IsOpened(): # Game main loop
while App.GetEvent(Event): # Event Handler
if Event.Type == sf.Event.Closed:
App.Close()
if Event.Type == sf.Event.KeyPressed:
if Event.Key.Code == sf.Key.Escape:
App.Close()
elif Event.Key.Code == sf.Key.Up:
Selection = (Selection - 1) % 4
elif Event.Key.Code == sf.Key.Down:
Selection = (Selection + 1) % 4
elif Event.Key.Code == sf.Key.Return:
Game(Selection)
Rectangle.SetY(200 + Selection*80)
App.Draw(Rectangle)
App.Draw(Title)
for i in range(0,4):
App.Draw(Strings[i])
App.Display()
App.Clear(BGColor)
# Initialize the window
ScreenWidth, ScreenHeight = 800, 600
App = sf.RenderWindow(sf.VideoMode(ScreenWidth,ScreenHeight,32), "PyWorm", sf.Style.Close) # Creates the window
BGColor = sf.Color(100,100,0,255)
App.SetFramerateLimit(30)
Menu()