1. ernestorx
  2. pygame

Commits

pygame  committed fb807c5

surfarray cleanups

  • Participants
  • Parent commits 717bd7f
  • Branches default

Comments (0)

Files changed (10)

File Setup.in

View file
-#flags needed to link each dependency
+#This Setup file is used by the setup.py script to configure the
+#python extensions. You will likely use the "config.py" which will
+#build a correct Setup file for you based on your system settings.
+#If not, the format is simple enough to edit by hand. First change
+#the needed commandline flags for each dependency, then comment out
+#any unavailable optional modules in the first optional section.
+
 
 #--StartConfig
 SDL = -I/usr/include/SDL -D_REENTRANT -lSDL
 #--EndConfig
 
 
-#base extensions (need sdl only, all of them needed)
+#the following modules are optional. you will want to compile
+#everything you can, but you can ignore ones you don't have
+#dependencies for, just comment them out
+
+font src/font.c $(SDL) $(FONT)
+image src/image.c $(SDL) $(IMAGE)
+mixer src/mixer.c $(SDL) $(MIXER)
+mixer_music src/music.c $(SDL) $(MIXER)
+
+
+
+#the following modules are also optional, but only require
+#python dependencies. the setup script can determine if these
+#are available at runtime, no need to change these
+
+surfarray src/surfarray.c $(SDL)    #requires Numeric
+
+
+
+#these modules are required for pygame to run. they only require
+#SDL as a dependency. these should not be altered
 
 base src/base.c $(SDL)
 cdrom src/cdrom.c $(SDL)
 joystick src/joystick.c $(SDL)
 
 
-#the following modules are optional. you will want to compile
-#everything you can, but you can ignore ones you don't have
-#dependencies for, just comment them out
-
-surfarray src/surfarray.c $(SDL)
-font src/font.c $(SDL) $(FONT)
-image src/image.c $(SDL) $(IMAGE)
-mixer src/mixer.c $(SDL) $(MIXER)
-mixer_music src/music.c $(SDL) $(MIXER)
-
-
 
 #the following are placeholders. setup.py can use them to help
 #auto-copy needed DLLs into the pygame installation folder.
-#you can simply ignore these lines under other OS, no need to
+#you can simply ignore these lines under non-windows, no need to
 #comment out.
 COPYLIB_smpeg $(SMPEG)

File TODO

View file
 
-Pygame is currently aiming for a 1.0 release near the end of the year.
+Pygame is currently aiming for a 1.0 release first quarter this year (2001).
 This doesn't mean pygame is in a useless state, it is in fact getting
 quite robust.
 

File WHATSNEW

View file
 #This is a list of changes in pygame's history.
 
+Jan 2, 2001
+	surfarray cleanups and improvements (still not 100%)
+
 Dec 22, 2000
 	timer threads properly shutdown
 

File config.py

View file
 """Quick tool to help setup the needed paths and flags
 in your Setup file. This will call the appropriate sub-config
 scripts automatically.
+
+each platform config file only needs a "main" routine
+that returns a list of instances. the instances must
+contain the following variables. 
+name: name of the dependency, as references in Setup (SDL, FONT, etc)
+inc_dir: path to include
+lib_dir: library directory
+lib: name of library to be linked to
+found: true if the dep is available
+cflags: extra compile flags
 """
 
 import sys, os, shutil
 
+
+if sys.version_info[0] < 2:
+    raise SystemExit, """Pygame requires python 2.0 or higher"""
+
+
 if sys.platform == 'win32':
     print 'Using WINDOWS configuration...\n'
     import config_win as CFG
 
 
 
+
 def confirm(message):
+    "ask a yes/no question, return result"
     reply = raw_input('\n' + message + ' [y/N]:')
     if reply and reply[0].lower() == 'y':
         return 1
     return 0
 
 
+def findbasepath(deps):
+    "find a common prefix in all paths"
+    allpaths = []
+    for d in deps:
+        if d.found:
+            allpaths.append(d.inc_dir)
+            allpaths.append(d.lib_dir)
+    basepath = os.path.commonprefix(allpaths)
+    lastslash = basepath.rfind('/')
+    if(lastslash < 3 or len(basepath) < 3):
+        basepath = ""
+    else:
+        basepath = basepath[:lastslash]
+    return basepath    
+
+
+def prepdep(dep, basepath):
+    "add some vars to a dep"
+    if not dep.found:
+        if dep.name == 'SDL': #fudge if this is unfound SDL
+            dep.line = 'SDL = -I/NEED_INC_PATH_FIX -L/NEED_LIB_PATH_FIX -lSDL'
+            dep.varname = '$('+dep.name+')'
+            dep.found = 1
+        return
+
+    inc = lid = lib = ""
+    if basepath:
+        if dep.inc_dir: inc = ' -I$(BASE)'+dep.inc_dir[len(basepath):]
+        if dep.lib_dir: lid = ' -L$(BASE)'+dep.lib_dir[len(basepath):]
+    else:
+        if dep.inc_dir: inc = ' -I' + dep.inc_dir
+        if dep.lib_dir: lid = ' -L' + dep.lib_dir
+    if dep.lib: lib = ' -l'+dep.lib
+    dep.line = dep.name+' =' + inc + lid + ' ' + dep.cflags + lib
+    dep.varname = '$('+dep.name+')'
+
+
+
+def writesetupfile(deps, basepath):
+    "create a modified copy of Setup.in"
+    origsetup = open('Setup.in', 'r')
+    newsetup = open('Setup', 'w')
+    line = ''
+    while line.find('#--StartConfig') == -1:
+        newsetup.write(line)
+        line = origsetup.readline()
+    while line.find('#--EndConfig') == -1:
+        line = origsetup.readline()
+
+    if basepath:
+        newsetup.write('BASE = ' + basepath + '\n')
+    for d in deps:
+        newsetup.write(d.line + '\n')
+
+    while line:
+        line = origsetup.readline()
+        useit = 1
+        for d in deps:
+            if line.find(d.varname)!=-1 and not d.found:
+                useit = 0
+                newsetup.write('#'+line)
+                break
+        if useit:          
+            newsetup.write(line)
+
+
+
+
 def main():
     if os.path.isfile('Setup'):
         if confirm('Backup existing "Setup" file'):
         if confirm('Remove old build directory (force recompile)'):
             shutil.rmtree('build', 0)
 
-    CFG.main()
+    deps = CFG.main()
+    if deps:
+        basepath = findbasepath(deps)
+        for d in deps:
+            prepdep(d, basepath)
+        writesetupfile(deps, basepath)
 
-    print """Doublecheck that the new "Setup" file looks correct, then
+
+    if os.path.isfile('Setup'):
+        print """Doublecheck that the new "Setup" file looks correct, then
 run "python setup.py install" to build and install pygame."""
-    
+    else:
+        print """There was an error creating the Setup file, check for errors
+or make a copy of "Setup.in" and edit by hand."""
+
+
 
 if __name__ == '__main__': main()
 

File config_unix.py

View file
 
 configcommand = 'sdl-config --version --cflags --libs'
 
+
+class Dependency:
+    inc_hunt = ['include']
+    lib_hunt = ['VisualC\\SDL\\Release', 'VisualC\\Release', 'Release', 'lib']
+    def __init__(self, name, checkhead, checklib, lib):
+        self.name = name
+        self.inc_dir = None
+        self.lib_dir = None
+        self.lib = lib
+        self.found = 0
+        self.checklib = checklib
+        self.checkhead = checkhead
+        self.cflags = ''
     
+    def configure(self, incdir, libdir):
+        inc = os.path.join(incdir, self.checkhead)
+        lib = os.path.join(libdir, self.checklib)
+        if os.path.isfile(inc) and glob(lib):
+            self.found = 1
 
-def writesetupfile(flags):
-    origsetup = open('Setup.in', 'r')
-    newsetup = open('Setup', 'w')
-    while 1:
-        line = origsetup.readline()
-        if not line: break
-        if line.startswith('SDL = '):
-            line = 'SDL = ' + flags + '\n'
-        newsetup.write(line)
-    
+
+DEPS = [
+    Dependency('SDL', 'SDL.h', 'libSDL.so', '-lSDL'),
+    Dependency('FONT', 'SDL_ttf.h.h', 'libSDL_ttf.so', '-lSDL_ttf'),
+    Dependency('IMAGE', 'SDL_image.h', 'libSDL_image.so', '-lSDL_image'),
+    Dependency('MIXER', 'SDL_mixer.h', 'libSDL_mixer.so', '-lSDL_mixer'),
+]
+
 
 def main():
-    configinfo = "-I/usr/include/SDL -D_REENTRANT -lSDL"
+    global DEPS
+    
     print 'calling "sdl-config"'
+    configinfo = "-I/usr/local/include/SDL -L/usr/local/lib -D_REENTRANT -lSDL"
     try:
         configinfo = os.popen(configcommand).readlines()
         print 'Found SDL version:', configinfo[0]
         raise SystemExit, """Cannot locate command, "sdl-config". Default SDL compile
 flags have been used, which will likely require a little editing."""
 
-    print '\n--Creating new "Setup" file...'
-    writesetupfile(configinfo)
-    print '--Finished'
+    print 'Hunting optional dependencies...'
+    incdir = libdir = ''
+    for arg in configinfo.split():
+        if arg.startswith('-I'):
+            incdir = arg[2:]
+        elif arg.startswith('-L'):
+            libdir = arg[2:]
+    #print 'INCDIR', incdir
+    #print 'LIBDIR', libdir
+    for d in DEPS:
+        d.configure(incdir, libdir)
 
+    d[0].inc_dir = None
+    d[0].lib_dir = None
+    d[0].cflags = configinfo
+
+    return DEPS
 
     
 if __name__ == '__main__':

File config_win.py

View file
 import os, sys, shutil
 from glob import glob
 
-huntpaths = ['..', '..'+os.sep+'..', '..'+os.sep+'*', \
-             '..'+os.sep+'..'+os.sep+'*']
+huntpaths = ['..', '..\\..', '..\\*', '..\\..\\*']
 
 
 class Dependency:
     inc_hunt = ['include']
-    lib_hunt = [os.path.join('VisualC', 'SDL', 'Release'),
-                os.path.join('VisualC', 'Release'),
-                'Release', 'lib']
+    lib_hunt = ['VisualC\\SDL\\Release', 'VisualC\\Release', 'Release', 'lib']
     def __init__(self, name, wildcard, lib, required = 0):
         self.name = name
         self.wildcard = wildcard
         self.inc_dir = None
         self.lib_dir = None
         self.lib = lib
-        self.varname = '$('+name+')'
-        self.line = ""
+        self.found = 0
+        self.cflags = ''
                  
     def hunt(self):
         parent = os.path.abspath('..')
         self.hunt()
         self.choosepath()
         if self.path:
+            self.found = 1
             self.inc_dir = self.findhunt(self.path, Dependency.inc_hunt)
             self.lib_dir = self.findhunt(self.path, Dependency.lib_hunt)
 
-    def buildline(self, basepath):
-        inc = lid = lib = " "
-        if basepath:
-            if self.inc_dir: inc = ' -I$(BASE)'+self.inc_dir[len(basepath):]
-            if self.lib_dir: lid = ' -L$(BASE)'+self.lib_dir[len(basepath):]
-        else:
-            if self.inc_dir: inc = ' -I' + self.inc_dir
-            if self.lib_dir: lid = ' -L' + self.lib_dir
-        if self.lib: lib = ' -l'+self.lib
-        self.line = self.name+' =' + inc + lid + lib
-            
-        
 
-DEPS = (
+
+
+DEPS = [
     Dependency('SDL', 'SDL-[0-9].*', 'SDL', 1),
     Dependency('FONT', 'SDL_ttf-[0-9].*', 'SDL_ttf'),
     Dependency('IMAGE', 'SDL_image-[0-9].*', 'SDL_image'),
     Dependency('MIXER', 'SDL_mixer-[0-9].*', 'SDL_mixer'),
 #copy only dependencies
     Dependency('SMPEG', 'smpeg-[0-9].*', 'smpeg')
-)
+]
 
 
-
-
-    
-
-def writesetupfile(DEPS, basepath):
-    origsetup = open('Setup.in', 'r')
-    newsetup = open('Setup', 'w')
-    line = ''
-    while line.find('#--StartConfig') == -1:
-        newsetup.write(line)
-        line = origsetup.readline()
-    while line.find('#--EndConfig') == -1:
-        line = origsetup.readline()
-
-    if not DEPS[0].path: #fudge SDL if not found
-        DEPS[0].line = 'SDL = -I/pathto/SDL/include -L/pathto/SDL/lib -lSDL'
-        DEPS[0].path = 'xxxx'
-
-    if basepath:
-        newsetup.write('BASE=' + basepath + '\n')
-    for d in DEPS:
-        newsetup.write(d.line + '\n')
-
-    while line:
-        line = origsetup.readline()
-        useit = 1
-        for d in DEPS:
-            if line.find(d.varname)!=-1 and not d.path:
-                useit = 0
-                newsetup.write('#'+line)
-                break
-        if useit:          
-            newsetup.write(line)
     
 
 def main():
     global DEPS
 
-    allpaths = []
+    if os.path.isdir('prebuilt'):
+        import config
+        if config.confirm('Use the win32 prebuilt directory'):
+            shutil.copyfile('prebuilt\\Setup', 'Setup')
+            return None
+
     for d in DEPS:
         d.configure()
-        if d.path:
-            allpaths.append(d.inc_dir)
-            allpaths.append(d.lib_dir)
 
-    basepath = os.path.commonprefix(allpaths)
-    lastslash = basepath.rfind('/')
-    if(lastslash < 3 or len(basepath) < 3):
-        basepath = ""
-    else:
-        basepath = basepath[:lastslash]
+    return DEPS    
 
-    for d in DEPS:
-        d.buildline(basepath)
 
-    writesetupfile(DEPS, basepath)
-    
+
 
 if __name__ == '__main__':
     print """This is the configuration subscript for Windows.

File setup.py

View file
 from distutils.ccompiler import new_compiler
 
 
-if sys.version_info[0] < 2:
-    raise SystemExit, """pygame requires python 2.0 or higher"""
-
-
 #headers to install
 headers = glob.glob(os.path.join('src', '*.h'))
 

File src/display.c

View file
 }
 
 
+PyObject* testgl1(PyObject* self, PyObject* arg)
+{
+	if(!PyArg_ParseTuple(arg, ""))
+		return NULL;
+	SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
+	SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
+	SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
+	SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
+	RETURN_NONE
+}
+
+PyObject* testgl2(PyObject* self, PyObject* arg)
+{
+	int r, g, b, d;
+	if(!PyArg_ParseTuple(arg, ""))
+		return NULL;
+	SDL_GL_GetAttribute( SDL_GL_RED_SIZE, &r );
+	SDL_GL_GetAttribute( SDL_GL_GREEN_SIZE, &g );
+	SDL_GL_GetAttribute( SDL_GL_BLUE_SIZE, &b );
+	SDL_GL_GetAttribute( SDL_GL_DEPTH_SIZE, &d );
+
+	printf("R,G,B,D = %d,%d,%d, %d\n", r, g, b, d);
+
+	RETURN_NONE
+}
+
 
 static PyMethodDef display_builtins[] =
 {
 	{ "iconify", iconify, 1, doc_iconify },
 	{ "toggle_fullscreen", toggle_fullscreen, 1, doc_toggle_fullscreen },
 
+	{ "testgl1", testgl1, 1, NULL },
+	{ "testgl2", testgl2, 1, NULL },
+
 	{ NULL, NULL }
 };
 

File src/pygame.h

View file
 #define PYGAMEAPI_BASE_FIRSTSLOT 0
 #define PYGAMEAPI_BASE_NUMSLOTS 10
 #ifndef PYGAMEAPI_BASE_INTERNAL
-#define PyExc_SDLError ((PyObject*)PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 0])
+#define PyExc_SDLError ((PyObject*)PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT])
 #define PyGame_RegisterQuit \
 			(*(void(*)(void(*)(void)))PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 1])
 #define ShortFromObj \

File src/surfarray.c

View file
 		return RAISE(PyExc_ValueError, "unsupport bit depth for 3D reference array");
 
 	/*must discover information about how data is packed*/
-	if(SDL_BYTEORDER == SDL_LIL_ENDIAN) /*intel-style*/
+	/*argh, endian not working, for now intelstyle will be the only way*/
+	if(1 || SDL_BYTEORDER == SDL_BIG_ENDIAN) /*intel-style*/
 	{
 		if(surf->format->Rmask == 0xff<<16 && 
 					surf->format->Gmask == 0xff<<8 &&
 	if(!array) return NULL;
 
 	data = (int*)((PyArrayObject*)array)->data;
-	
+#if 1	
 	switch(surf->format->BytesPerPixel)
 	{
 	case 1:
 		for(loopy = 0; loopy < surf->h; ++loopy)
 		{
 			char* pix = (char*)(((char*)surf->pixels)+loopy*surf->pitch);
-			char* end = (char*)(((char*)pix)+surf->w*surf->format->BytesPerPixel);
-			while(pix <= end)
+			char* end = (char*)(((char*)pix)+surf->w);
+			while(pix < end)
 				*data++ = *pix++;
 		}break;
 	case 2:
 		for(loopy = 0; loopy < surf->h; ++loopy)
 		{
 			short* pix = (short*)(((char*)surf->pixels)+loopy*surf->pitch);
-			short* end = (short*)(((char*)pix)+surf->w*surf->format->BytesPerPixel);
-			while(pix <= end)
+			short* end = (short*)(((char*)pix)+surf->w*2);
+			while(pix < end)
 				*data++ = *pix++;
 		}break;
 	case 3:
 		for(loopy = 0; loopy < surf->h; ++loopy)
 		{
-			char* pix = (char*)(((char*)surf->pixels)+loopy*surf->pitch);
-			char* end = (char*)(((char*)pix)+surf->w*surf->format->BytesPerPixel);
-			while(pix <= end)
-			{
-				*data++ = (*(int*)pix) >> 8;
-				pix += 3;
-			}
+			unsigned char* pix = (unsigned char*)(((char*)surf->pixels)+loopy*surf->pitch);
+			unsigned char* end = pix+surf->w*3;
+			while(pix < end)
+				{*data++ = (pix[0]) + (pix[1]<<8) + (pix[2]<<16); pix += 3;}
 		}break;
 	default: /*case 4*/
 		for(loopy = 0; loopy < surf->h; ++loopy)
 		{
 			int* pix = (int*)(((char*)surf->pixels)+loopy*surf->pitch);
-			int* end = (int*)(((char*)pix)+surf->w*surf->format->BytesPerPixel);
-			while(pix <= end)
+			int* end = (int*)(((char*)pix)+surf->w*4);
+			while(pix < end)
 				*data++ = *pix++;
 		}break;
 	}
-
+#endif
 	return array;
 }
 
 
 PyObject* array3d(PyObject* self, PyObject* arg)
 {
-	int dim[3], loopy;
+	int dim[3];
 	Uint8* data;
 	PyObject* array;
 	SDL_Surface* surf;
+	SDL_Surface* temp;
 	SDL_PixelFormat* format;
-	int Rmask, Gmask, Bmask, Rshift, Gshift, Bshift;
+	SDL_Rect bounds;
+	Uint32 surface_flags, colorkey;
+	Uint8 alpha;
 
 	if(!PyArg_ParseTuple(arg, "O!", &PySurface_Type, &array))
 		return NULL;
 	dim[1] = surf->h;
 	dim[2] = 3;
 
-	if(surf->format->BytesPerPixel <= 0 || surf->format->BytesPerPixel > 4)
+	if(format->BytesPerPixel < 1 || format->BytesPerPixel > 4)
 		return RAISE(PyExc_ValueError, "unsupport bit depth for surface array");
 
 	array = PyArray_FromDims(3, dim, PyArray_UBYTE);
 	if(!array) return NULL;
 
 	data = (Uint8*)((PyArrayObject*)array)->data;
-	Rmask = format->Rmask; Gmask = format->Gmask; Bmask = format->Bmask;
-	Rshift = format->Rshift; Gshift = format->Gshift; Bshift = format->Bshift;
-	
-	switch(surf->format->BytesPerPixel)
-	{
-	case 1:
-		return RAISE(PyExc_ValueError, "colormaps unsupported");
-	case 2:
-		for(loopy = 0; loopy < surf->h; ++loopy)
-		{
-			short* pix = (short*)(((char*)surf->pixels)+loopy*surf->pitch);
-			short* end = (short*)(((char*)pix)+surf->w*surf->format->BytesPerPixel);
-			while(pix <= end)
-			{
-				short color = *pix++;
-				*data++ = (color&Rmask)>>Rshift;
-				*data++ = (color&Gmask)>>Gshift;
-				*data++ = (color&Bmask)>>Bshift;
-			}
-		}break;
-	case 3:
-		for(loopy = 0; loopy < surf->h; ++loopy)
-		{
-			char* pix = (char*)(((char*)surf->pixels)+loopy*surf->pitch);
-			char* end = (char*)(((char*)pix)+surf->w*surf->format->BytesPerPixel);
-			while(pix <= end)
-			{
-				int color = (*(int*)pix++) >> 8;
-				*data++ = (color&Rmask)>>Rshift;
-				*data++ = (color&Gmask)>>Gshift;
-				*data++ = (color&Bmask)>>Bshift;
-			}
-		}break;
-	default: /*case 4*/
-		for(loopy = 0; loopy < surf->h; ++loopy)
-		{
-			int* pix = (int*)(((char*)surf->pixels)+loopy*surf->pitch);
-			int* end = (int*)(((char*)pix)+surf->w*surf->format->BytesPerPixel);
-			while(pix <= end)
-			{
-				int color = *pix++;
-				*data++ = (color&Rmask)>>Rshift;
-				*data++ = (color&Gmask)>>Gshift;
-				*data++ = (color&Bmask)>>Bshift;
-			}
-		}break;
+	temp = SDL_CreateRGBSurfaceFrom(data, surf->w, surf->h, 24,
+				surf->w*3, 0xFF, 0xFF<<8, 0xFF<<16, 0);
+
+	/*stash original surface alpha states*/
+	surface_flags = surf->flags;
+	if ( (surface_flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY ) {
+		colorkey = format->colorkey;
+		SDL_SetColorKey(surf, 0, 0);
 	}
+	if ( (surface_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
+		alpha = format->alpha;
+		SDL_SetAlpha(surf, 0, 0);
+	}
+
+	/* Copy over the image data */
+	bounds.x = 0;
+	bounds.y = 0;
+	bounds.w = surf->w;
+	bounds.h = surf->h;
+	SDL_LowerBlit(surf, &bounds, temp, &bounds);
+
+	/* Clean up the original surface, and update converted surface */
+	if((surface_flags & SDL_SRCCOLORKEY) == SDL_SRCCOLORKEY)
+		SDL_SetColorKey(surf, surface_flags&(SDL_SRCCOLORKEY|SDL_RLEACCELOK), 
+					colorkey);
+	if((surface_flags & SDL_SRCALPHA) == SDL_SRCALPHA)
+		SDL_SetAlpha(surf, surface_flags&SDL_SRCALPHA, alpha);
+
+	SDL_FreeSurface(temp);
 
 	return array;
 }
 		stridez = array->strides[1];
 		sizex = 1;
 		sizey = array->dimensions[0];
-#if 0 /*kinda like a scalar here, use normal map_rgb*/
+#if 1 /*kinda like a scalar here, use normal map_rgb*/
 	case 1: /*single color*/
 		dims[0] = 1;
 		newarray = PyArray_FromDims(1, dims, PyArray_INT);
 		char* data = ((char*)surf->pixels) + surf->pitch * loopy; \
 		char* pix = array->data + stridey * loopy; \
 		for(loopx = 0; loopx < sizex; ++loopx) { \
+			*data++ = (char)*(SRC*)(pix+stridez2); \
+			*data++ = (char)*(SRC*)(pix+stridez); \
 			*data++ = (char)*(SRC*)(pix); \
-			*data++ = (char)*(SRC*)(pix+stridez); \
-			*data++ = (char)*(SRC*)(pix+stridez2); \
 			pix += stridex; \
 	}	}