'osgl-lite.bas--------------------------------------------------------------------------------------------------------------------------

'http://www.darkphear.com

'http://cmcgames.blogspot.com

'Copyright (C) Cleber de Mattos Casali. All rights reserved.

'This file is released under the terms of the GNU General Public License (GPL) as
'published by the Free Software Foundation, GPL version 2 or any later version.

'Please give me credit if you use it.


'FreeBASIC is an excellent, fast and completely free, open-source BASIC compiler.
'Check it at http://www.freebasic.net


dim as string author="This file is Copyright (C) Cleber de Mattos Casali. All rights reserved. It may not be sold without the written permission of the copyright holder. This software is provided as is without any express or implied warranty."
author=""

'osgl (Old School Game Layer)
'by Cleber de Mattos Casali
#print "Now compiling osgl..."

#if __FB_LANG__="fb"
	#define FBImage FB.Image
#else
	#define FBImage any
#endif

dim shared osgl_begintimer as double
osgl_begintimer=timer

dim shared osgl_freemembegin as uinteger
osgl_freemembegin=fre

dim shared osgl_quitprogram as integer=0

dim shared osgl_gamelevel as integer=1
function osgl_gamelevel_ as integer'
	function=osgl_gamelevel
end function

'#define _osgl_noscreen_
'#define _osgl_nodownloads_
'#define _osgl_nosound_
'#define _osgl_nomusic_
'#define _osgl_nodebug_
'#define _osgl_debug_
'#define _osgl_debugfps_
'#define _osgl_noconsole_
'#define _osgl_softrender_
'#define _osgl_forceappname_ "osgl"
'#define _osgl_appfullname_ "Old School Games Library"

'#define _osgl_xscreen_ 800
'#define _osgl_yscreen_ 600
'#define _osgl_windowed_

#IFDEF __FB_DOS__
    #DEFINE _osgl_softrender_
#ENDIF

#IFNDEF _osgl_softrender_
    #include once "GL/gl.bi"
'    #ifdef __FB_WIN32__
'        #include once "GL/glext.bi"
'    #endif
#ENDIF

#ifndef GL_BGRA
	#define GL_BGRA &h80E1
#endif

#ifndef GL_COMPRESSED_RGBA
	#define GL_COMPRESSED_RGBA &h84EE
#endif

#ifndef GL_TEXTURE_COMPRESSION_HINT
	#define GL_TEXTURE_COMPRESSION_HINT &h84EF
#endif

#ifdef __FB_WIN32__
	#include once "windows.bi"
	#include once "win\shellapi.bi"
#endif

function osgl_windowsversion as integer
#ifdef __FB_WIN32__
dim WindowsVersion as OSVERSIONINFO
WindowsVersion.dwOSVersionInfoSize = len(OSVERSIONINFO)
GetVersionEx(@WindowsVersion)
function=WindowsVersion.dwMajorVersion
#else
function=0
#endif
end function

#include once "crt.bi"
#include once "fbgfx.bi"
#ifndef __FB_WIN32__
	#define _osgl_zlibdynamic_
#endif
#ifndef _osgl_zlibdynamic_
	#define PNG_STATICZ
#endif
#include once "fbpng.bi" 'Thank you Simon Nash - yetifoot from FreeBASIC Forums)
'#include once "png_image.bi"

'#include once "pload2.bas"

#IFNDEF png_destroy
    #DEFINE png_destroy imagedestroy
#ENDIF

#ifndef NULL
#define NULL cptr(Any Ptr,0)
#endif

dim shared returnappname as string
dim shared returnhomedir as string
'printconsole e printdebug
dim shared debug as integer =1
dim shared consoleon as integer =0
dim shared CONSOLEHANDLE as integer
#define printconsole if consoleon then print #CONSOLEHANDLE,
#define printdebug if debug then print #CONSOLEHANDLE,"DEBUG:",

#ifdef _osgl_debug_
    debug=1
#endif

#ifdef _osgl_nodebug_
    debug=0
#endif

#ifdef _osgl_noconsole_
    consoleon=0:debug=0
#endif

if InStr(lcase(command()), "-quiet")=0 and InStr(lcase(command()), "-noconsole")=0 then
   consoleon=1
   CONSOLEHANDLE=freefile
   if (open cons(for output, as #CONSOLEHANDLE))<>0 then consoleon=0:debug=0
else
    consoleon=0:debug=0
end if

function freefile2() as integer
dim as integer ffile
	do
		ffile = FREEFILE
		if ffile=0 then
			printdebug "WARNING: FREEFILE returned 0"
			CLOSE 'close all
			if consoleon then'reopen console
				CONSOLEHANDLE=freefile
				if (open cons(for output, as #CONSOLEHANDLE))<>0 then consoleon=0:debug=0
			end if
		end if
	loop until ffile<>0
function=ffile
end function

#ifndef __DATE_ISO__
	#define __DATE_ISO__ (mid(__DATE__,7,4)+"."+mid(__DATE__,1,2)+"."+mid(__DATE__,4,2))
#endif

#define osgl_builddate __DATE_ISO__

printconsole
printconsole " * O S G L   E N G I N E * "
printconsole
printconsole "by Cleber de Mattos Casali"
printconsole
printconsole "version 0.2."+osgl_builddate
printdebug "Built with "+__FB_SIGNATURE__+"."
printconsole

'diretorios do PATH
dim shared as string _osgl_execpath()
dim as string envpath=environ("PATH")
printdebug "PATH="+envpath

'transforma em matriz
declare sub String2Array(mystring as string, separator as string=",", stringarray() as string,byval keepseparator as integer=0)
String2Array(envpath,":", _osgl_execpath())
envpath=""

'adiciona / e passa o /usr/bin para primeira posição
for i as integer=1 to ubound(_osgl_execpath)
	_osgl_execpath(i)+="/"
	if _osgl_execpath(i)="/usr/bin/" then swap _osgl_execpath(i),_osgl_execpath(1)
next i

'mostra (debug)
for i as integer=1 to ubound(_osgl_execpath)
	printdebug "_osgl_execpath("+str(i)+")="+_osgl_execpath(i)
next i

function exec2(tfn as string, param as string=" ") as integer
#IFDEF __FB_WIN32__
Dim As Integer cexit,res
Dim As String verb="open"
Dim As SHELLEXECUTEINFO shif
Dim prevhWnd As HWND
dim curhwnd as HWND

'dim as integer windowxid
'ScreenControl 2, windowxid
'shif.hwnd=windowxid
shif.hwnd=NULL
'SEE_MASK_NOASYNC=&h100
shif.fMask=SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_NO_UI or &h100
shif.lpVerb=Strptr(verb)
shif.lpFile=Strptr(tfn)
shif.lpParameters=Strptr(param)
'shif.nShow=SW_SHOWminimized ' loads minimized
shif.nShow=SW_HIDE 'hidden
shif.cbSize=Len(shif)

SetLastError(0)

res=ShellExecuteEx(@shif)
If res=0 Then
    printdebug "ShellExecuteEx failed"
	function=-1
	exit function
end If

Do
    Sleep 1,1
    res=GetExitCodeProcess(shif.hProcess,@cexit)
Loop While res<>0 And cexit=STILL_ACTIVE '259

printdebug tfn;" has terminated. Returned code "+str(cexit)
function=cexit
#else
if ubound(_osgl_execpath)=0 then printconsole "ERROR : exec2 : osgl not initialized!" : function=-1 : exit function
'linux & etc
'só executar se o arquivo existir, caso contrario causa bug no xserver
dim as integer retval=-1
'printconsole "ble1"
if dir(tfn)<>"" then
	'com path
	retval=exec(tfn,param)
	'printconsole "ble"
else
	'sem path
	dim as string tfn2
	for i as integer =1 to ubound(_osgl_execpath)
		tfn2=_osgl_execpath(i)+tfn
		printconsole tfn2
		if dir(tfn2)<>"" then
			'printconsole "run"
			retval=exec(tfn2,param)
		else
			retval=-1
		end if
		if retval<>-1 then exit for
	next i
end if
function=retval
#endif
end function

#define SET_ALPHA_PRIMITIVES 104

'define the _SDL_LINK_ variable to link SDL dynamically. Otherwise, it will be loaded at runtime.
'#define _SDL_LINK_

'Definições de Audio
#ifndef maxsfx
    #define maxsfx 127
#endif

'in case we need to disable audio
declare sub osgl_DisableAudio()
#ifdef _osgl_nosound_
    'don't link SDL if _osgl_nosound_ is defined
    #undef _SDL_LINK_
    osgl_disableaudio
#ENDIF

'link SDL dynamically
#ifndef _osgl_nosound_
#IFDEF _SDL_LINK_
    #include once "SDL/SDL.bi"
	#include once "SDL/SDL_mixer.bi"
#ENDIF
#endif

#IFNDEF _SDL_LINK_
    type Mix_Chunk as any
    type Mix_Music as any
#ENDIF

type soundtype
    useSDL as integer
    started as integer
    disabled as integer
    sfx_on as integer
    music_on as integer
    audio_rate as integer
'    audio_format as Uint16
    audio_format as ushort
    audio_channels as integer
    audio_buffers as integer
    audio_mixchannels as integer
    music as Mix_Music ptr
	musicfile as string
	musicplaying as integer
'    music as any ptr
'    sfx(maxsfx) as any ptr
	musicvolume as single=1.0
	sfxvolume as single=1.0
end type
dim shared sound as soundtype

#define osgl_soundchannels sound.audio_mixchannels
function osgl_soundchannels_ as integer
	function=sound.audio_mixchannels
end function

dim shared lastsfx as uinteger=0
dim shared soundsfx() as Mix_Chunk ptr

'----------------------------------------dynamic SDL (as plugin)
Dim shared As Any Ptr libsdl,libsdlmixer
dim shared as any ptr libjoyrumble
#IFNDEF _SDL_LINK_

'SDL constants and types
#define SDL_INIT_AUDIO &h00000010
#define SDL_INIT_JOYSTICK &h00000200

#define AUDIO_U8 &h0008
#define AUDIO_S8 &h8008
#define AUDIO_U16LSB &h0010
#define AUDIO_S16LSB &h8010
#define AUDIO_U16MSB &h1010
#define AUDIO_S16MSB &h9010
#define AUDIO_U16 &h0010
#define AUDIO_S16 &h8010

#define SDL_LIL_ENDIAN 1234
#define SDL_BIG_ENDIAN 4321

#if defined(__FB_WIN32__) or defined(__FB_LINUX__) or defined(__FB_FREEBSD__) or defined(__FB_NETBSD__) or defined(__FB_OPENBSD__) or defined(__FB_XBOX__) or defined(__FB_DOS__)
	#define SDL_BYTEORDER SDL_LIL_ENDIAN
	#define AUDIO_U16SYS AUDIO_U16LSB
	#define AUDIO_S16SYS AUDIO_S16LSB
#else
	#define SDL_BYTEORDER SDL_BIG_ENDIAN
	#define AUDIO_U16SYS AUDIO_U16MSB
	#define AUDIO_S16SYS AUDIO_S16MSB
#endif

#define MIXER_DEFAULT_FORMAT AUDIO_S16SYS

type Uint8 as ubyte
type Sint8 as byte
type Uint16 as ushort
type Sint16 as short
type Uint32 as uinteger
type Sint32 as integer
type Uint64 as ulongint
type Sint64 as longint

'SDL Functions
dim shared     SDL_Init as function cdecl (byval flags as Uint32) as integer
dim shared     SDL_Quit as function cdecl() as integer
dim shared     SDL_RWFromFile as function cdecl(byval file as zstring ptr, byval mode as zstring ptr) as any ptr
dim shared     SDL_RWFromMem as function cdecl(byval mem as any ptr, byval size as integer) as any ptr
'dim shared 	SDL_NumJoysticks as function cdecl () as integer
dim shared     SDL_JoystickName as function cdecl(byval index as integer) as zstring ptr
dim shared     Mix_QuerySpec as function cdecl(byval frequency as integer ptr, byval format as Uint16 ptr, byval channels as integer ptr) as integer
dim shared     Mix_OpenAudio as function cdecl(byval frequency as integer=44100, byval format as Uint16=MIXER_DEFAULT_FORMAT, byval channels as integer=2, byval chunksize as integer=4096) as integer
dim shared    Mix_LoadWAV_RW as function cdecl(byval src as any ptr, byval freesrc as integer=1) as any ptr
#define         Mix_LoadWav(file) Mix_LoadWAV_RW(SDL_RWFromFile(file, "rb"), 1)
dim shared     Mix_PlayChannelTimed as function cdecl(byval channel as integer=-1, byval chunk as any ptr, byval loops as integer=0, byval ticks as integer=-1) as integer
#define         Mix_PlayChannel(channel,chunk,loops) Mix_PlayChannelTimed(channel,chunk,loops,-1)
dim shared     Mix_SetPanning as function cdecl(byval channel as integer=-1, byval left as Uint8=255, byval right as Uint8=255) as integer
dim shared    Mix_FreeChunk as function cdecl(byval chunk as any ptr) as integer
dim shared     Mix_LoadMUS as function cdecl(byval file as zstring ptr) as any ptr
dim shared     Mix_LoadMUS_RW as function cdecl(byval src as any ptr, byval freesrc as integer=1) as any ptr
dim shared    Mix_PlayMusic as function cdecl(byval music as any ptr, byval loops as integer) as integer
dim shared    Mix_HaltMusic as function cdecl() as integer
dim shared    Mix_FreeMusic as function cdecl(byval music as any ptr) as integer
dim shared    Mix_CloseAudio as function cdecl() as integer
dim shared    Mix_VolumeMusic as function cdecl(byval volume as integer) as integer
dim shared    Mix_AllocateChannels as function cdecl(byval numchans as integer) as integer
'#define osgl_numberofjoy SDL_NumJoysticks()
#define osgl_numberofjoy _osgl_numberofjoy
#define osgl_joyname(j) osgl_playerinput(j).devicename

#define osgl_rnd(min,max) (min+int(rnd*(max-min+1)))
#define osgl_probability(value) (int(rnd*101)<value)


declare sub osgl_popup(byval title as string,byval message as string)

declare function appname() as string

sub osgl_SDLdyload
'Load SDL dynamically

#ifdef __FB_WIN32__
    libsdl=DyLibLoad("SDL.dll")
    if libsdl=0 then libsdl=DyLibLoad(exepath()+"\SDL.dll")
    if libsdl=0 then libsdl=DyLibLoad(exepath()+"\dll\SDL.dll")
    if libsdl=0 then libsdl=DyLibLoad(exepath()+"\dll32\SDL.dll")
    if libsdl=0 then libsdl=DyLibLoad(exepath()+"\dll64\SDL.dll")
    if libsdl=0 then
        printconsole "SDL : could not load SDL.dll"
	osgl_popup "WARNING","Could not load SDL.dll. Sound will be disabled."
	osgl_disableaudio
    else
        printconsole "SDL : SDL is loaded! Pointer = " ,libsdl
    end if

    libsdlmixer=DyLibLoad("SDL_mixer.dll")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(exepath()+"\SDL_mixer.dll")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(exepath()+"\dll\SDL_mixer.dll")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(exepath()+"\dll32\SDL_mixer.dll")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(exepath()+"\dll64\SDL_mixer.dll")
    if libsdlmixer=0 then
        printconsole "SDL : could not load SDL_mixer.dll"
	osgl_popup "WARNING","Could not load SDL_mixer.dll. Sound will be disabled."
	osgl_disableaudio
    else
        printconsole "SDL : SDL_mixer is loaded! Pointer = ",libsdlmixer
    end if
#else
    SetEnviron("LD_LIBRARY_PATH="+chr(34)+environ("LD_LIBRARY_PATH")+":"+exepath()+"/lib32")+chr(34)
    printdebug "Init : LD_LIBRARY_PATH="+environ("LD_LIBRARY_PATH")
    libsdl=DyLibLoad("libSDL.so")
    if libsdl=0 then libsdl=DyLibLoad("libSDL-1.2.so")
    if libsdl=0 then libsdl=DyLibLoad("libSDL-1.2.so.0")
    if libsdl=0 then libsdl=DyLibLoad(exepath()+"/libSDL.so")
    if libsdl=0 then libsdl=DyLibLoad(exepath()+"/libSDL-1.2.so.0")
    if libsdl=0 then libsdl=DyLibLoad(exepath()+"/lib32/libSDL.so")
    if libsdl=0 then libsdl=DyLibLoad(exepath()+"/lib32/libSDL-1.2.so.0")
    if libsdl=0 then libsdl=DyLibLoad(exepath()+"/lib/libSDL.so")
    if libsdl=0 then libsdl=DyLibLoad(exepath()+"/lib/libSDL-1.2.so.0")
    if libsdl=0 then libsdl=DyLibLoad("/usr/lib/libSDL.so")
    if libsdl=0 then libsdl=DyLibLoad("/usr/lib/libSDL-1.2.so.0")
    if libsdl=0 then libsdl=DyLibLoad(dir("/usr/lib/libSDL-1.2.so.*"))
    if libsdl=0 then libsdl=DyLibLoad(dir("/usr/lib/libSDL-1.*"))
    if libsdl=0 then libsdl=DyLibLoad("/usr/lib32/libSDL.so")
    if libsdl=0 then libsdl=DyLibLoad("/usr/lib32/libSDL-1.2.so.0")
    if libsdl=0 then libsdl=DyLibLoad(dir("/usr/lib32/libSDL-1.2.so.*"))
    if libsdl=0 then libsdl=DyLibLoad(dir("/usr/lib32/libSDL-1.*"))
    if libsdl=0 then libsdl=DyLibLoad("/usr/lib/i386-linux-gnu/libSDL.so")
    if libsdl=0 then libsdl=DyLibLoad("/usr/lib/i386-linux-gnu/libSDL-1.2.so.0")
    if libsdl=0 then libsdl=DyLibLoad(dir("/usr/lib/i386-linux-gnu/libSDL-1.2.so.*"))
    if libsdl=0 then libsdl=DyLibLoad(dir("/usr/lib/i386-linux-gnu/libSDL-1.*"))
   	if libsdl=0 then libsdl=dylibload("/usr/lib/"+appname()+"/libSDL.so")
	if libsdl=0 then libsdl=dylibload("/usr/lib/i386-linux-gnu/"+appname()+"/libSDL.so")
	if libsdl=0 then libsdl=dylibload("/usr/lib32/"+appname()+"/libSDL.so")

    if libsdl=0 then
        printconsole "SDL : could not load libSDL.so or libSDL-1.2.so.0"
		osgl_popup "WARNING","Could not load libSDL. Sound will be disabled."
		osgl_disableaudio
    else
        printconsole "SDL : libSDL is loaded!"
    end if

    libsdlmixer=DyLibLoad("libSDL_mixer.so")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad("libSDL_mixer-1.2.so")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad("libSDL_mixer-1.2.so.0")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(exepath()+"/libSDL_mixer.so")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(exepath()+"/libSDL_mixer-1.2.so.0")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(exepath()+"/lib32/libSDL_mixer.so")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(exepath()+"/lib32/libSDL_mixer-1.2.so.0")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(exepath()+"/lib/libSDL_mixer.so")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(exepath()+"/lib/libSDL_mixer-1.2.so.0")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad("/usr/lib/libSDL_mixer.so")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad("/usr/lib/libSDL_mixer-1.2.so.0")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad("/usr/lib32/libSDL_mixer.so")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad("/usr/lib32/libSDL_mixer-1.2.so.0")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad("/usr/lib64/libSDL_mixer.so")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad("/usr/lib64/libSDL_mixer-1.2.so.0")
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(dir("/usr/lib/libSDL_mixer-1.2.so.*"))
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(dir("/usr/lib/libSDL_mixer-1.*"))
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(dir("/usr/lib32/libSDL_mixer-1.2.so.*"))
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(dir("/usr/lib32/libSDL_mixer-1.*"))
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(dir("/usr/lib/i386-linux-gnu/libSDL_mixer-1.2.so.*"))
    if libsdlmixer=0 then libsdlmixer=DyLibLoad(dir("/usr/lib/i386-linux-gnu/libSDL_mixer-1.*"))
   	if libsdlmixer=0 then libsdlmixer=dylibload("/usr/lib/"+appname()+"/libSDL_mixer.so")
	if libsdlmixer=0 then libsdlmixer=dylibload("/usr/lib/i386-linux-gnu/"+appname()+"/libSDL_mixer.so")
	if libsdlmixer=0 then libsdlmixer=dylibload("/usr/lib32/"+appname()+"/libSDL_mixer.so")
    if libsdlmixer=0 then
        printconsole "SDL : could not load libSDL_mixer.so or libSDL_mixer-1.2.so.0"
	osgl_popup "WARNING","Could not load libSDL_mixer. Sound will be disabled."
	osgl_disableaudio
    else
        printconsole "SDL : libSDL_mixer is loaded!"
    end if
#endif

'inicia SDL functions
    SDL_Init=DyLibSymbol(libsdl,"SDL_Init")
    SDL_Quit=DyLibSymbol(libsdl,"SDL_Quit")
    SDL_RWFromFile=DyLibSymbol(libsdl,"SDL_RWFromFile")
    SDL_RWFromMem=DyLibSymbol(libsdl,"SDL_RWFromMem")
    'SDL_NumJoysticks=DyLibSymbol(libsdl,"SDL_NumJoysticks")
    SDL_JoystickName=DyLibSymbol(libsdl,"SDL_JoystickName")
    Mix_QuerySpec=DyLibSymbol(libsdlmixer,"Mix_QuerySpec")
    Mix_OpenAudio=DyLibSymbol(libsdlmixer,"Mix_OpenAudio")
    Mix_LoadWAV_RW=DyLibSymbol(libsdlmixer,"Mix_LoadWAV_RW")
    Mix_PlayChannelTimed=DyLibSymbol(libsdlmixer,"Mix_PlayChannelTimed")
    Mix_SetPanning=DyLibSymbol(libsdlmixer,"Mix_SetPanning")
    Mix_FreeChunk=DyLibSymbol(libsdlmixer,"Mix_FreeChunk")
    Mix_LoadMUS=DyLibSymbol(libsdlmixer,"Mix_LoadMUS")
    Mix_LoadMUS_RW=DyLibSymbol(libsdlmixer,"Mix_LoadMUS_RW")
    Mix_PlayMusic=DyLibSymbol(libsdlmixer,"Mix_PlayMusic")
    Mix_HaltMusic=DyLibSymbol(libsdlmixer,"Mix_HaltMusic")
    Mix_FreeMusic=DyLibSymbol(libsdlmixer,"Mix_FreeMusic")
    Mix_CloseAudio=DyLibSymbol(libsdlmixer,"Mix_CloseAudio")
    Mix_VolumeMusic=DyLibSymbol(libsdlmixer,"Mix_VolumeMusic")
    Mix_AllocateChannels=DyLibSymbol(libsdlmixer,"Mix_AllocateChannels")

'dim shared    Mix_VolumeMusic as function cdecl(byval volume as integer) as integer

if SDL_Init=0 then
        printconsole "SDL : could not init SDL"
	osgl_popup "WARNING","Could not init SDL. Sound will be disabled."
	osgl_disableaudio
end if

end sub

#ENDIF
'----------------------------------------END dynamic SDL (as plugin)

'
#define osgl_ygroundfunc(y1,z1,y2,z2,z) (y1)+((z)-(z1))*((y2)-(y1))/((z2)-(z1))
#define osgl_cameradistance -myscreen.eyez
#define osgl_near(aa) myscreen.near=aa:osgl_set3dscreen()
#define osgl_far(aa) myscreen.far=aa:osgl_set3dscreen()

#macro osgl_texturecompression(aa)
	if aa=0 then
	    myscreen.textureformat=GL_RGBA
        else
            if myscreen.usetexturecompression=1 then myscreen.textureformat=GL_COMPRESSED_RGBA
	end if
#endmacro

#define osgl_texturesizex(aa) texturearray(aa).xslicesize
#define osgl_texturesizey(aa) texturearray(aa).yslicesize

'angles
Const PI as double = Atn(1)*4
Const PIx2 As double  = pi*2
Const PI_2 As double  = pi/2
Const PI_180 as double = PI/180
#define RADIANS(x) ((x)*PI_180)
#define DEGREES(x) ((x)/PI_180)

function osgl_angledifference(byval firstAngle as double, byval secondAngle as double) as double
        dim as double adifference = secondAngle - firstAngle
        while adifference < -180 : adifference += 360 : wend
        while adifference > 180  : adifference -= 360 : wend
        function=adifference
end function


#IFDEF _osgl_softrender_
	type GLenum as integer
#ENDIF

#ifndef osgl_maxmousebutton
    #define osgl_maxmousebutton 3
#endif

#macro osgl_clearkeyboardbuffer()
	WHILE LEN(INKEY) : WEND
#endmacro

'restaura tela
type screeninfotype
	handle as integer=0
    started as integer=0
    x as integer
    y as integer
    depth as integer=32
    vsync as integer=1
    trustvsync as integer=1
    windowxid as integer=0
    xyproportion as single
    stereo3d as integer=0
    secondeye as integer=0
    anaglyph as integer=1
    eyedistance as integer=8
    drawingtotexture as integer=0
    screencopytexture as integer=0
    realx as integer
    realy as integer
	ratiox as single
	ratioy as single
    fovy as single=45
    tanfovy as single=1.207
    eyez as single=0.000001
    near as integer=10
    far as integer=5000
    camerax as single=0
    cameray as single=0
    cameraz as single=0
    cameraxl as single=0
    camerayl as single=0
    camerazl as single=0
    camerax2 as single=0
    cameray2 as single=0
    cameraz2 as single=0
    cameraxl2 as single=0
    camerayl2 as single=0
    camerazl2 as single=0
    cameraxa as single=0
    cameraya as single=0
    cameraza as single=0
    zoomx as single=0
    zoomy as single=0
    zoomxcenter as single=0
    zoomycenter as single=0
    objmode as integer=0
    widescreen as integer=1
    blackborders as integer=0
    cutpixels as integer=0
    xcutpixels as integer=0
    widepixels as integer=0
    fullscreen as integer
    windownoframe as integer=0
    mousex as integer=0
    mousey as integer=0
    mousexold as integer=0
    mouseyold as integer=0
    mousez as integer=0
    mousezold as integer=0
    mousebuttons as integer=0
    mousebtn(-1 to osgl_maxmousebutton) as integer
    mouseclip as integer=1
	mouseinactive as integer=999999
	mousetouchscreen as integer=0
    originalx as integer
    originaly as integer
    originaldepth as integer
    monitorrefresh as integer
    currentfontsize as integer=8
'    rendermode as integer=0 '2d=0 3d=1
    syncmode as integer=0 'osgl_sleep=0 fb=1 osgl_threads=2
    virgin as integer=0 'use osgl_syncbuffers to prevent flickering
    cansleep as integer=0
	sleepframe as integer=0
    usingdepthbuffer as integer
    maxtexturesize as integer
	currenttexture as integer
	currentblendmode as integer
    nonpot as integer
    nonsquare as integer
    usebgra as integer=-1
    useconstantcolor as integer=1
    useopengl as integer=1
    usetexturecompression as integer=-1
    usefrontbuffer as integer=-1
    #IFNDEF _osgl_softrender_
		textureformat as glenum = GL_RGBA
	#ELSE
		textureformat as integer=0
    #ENDIF
    numpages as integer=1
    antialias as integer=0
    filter as integer=1
    alphaprimitives as integer=0
    gfxnoswitch as integer=0
    switches as integer
    glversion as string
    glrenderer as string
    glvendor as string
    glextensions as string
    framesdrawn as ulongint
    FadeInalpha as integer
    FadeIneffect as integer
    fadeinspeed as single
    fps as integer =0
    fpstimer as double =0
    fpscounter as integer =0
    mysyncrate as integer =0
    maxsyncrate as integer =0
    interframetimer as double =0
    interframetime as double =0
    interframetime2 as double =0
    interframeadjust as double =0
    frameskipmode as integer=-1 '0=auto 1=on -1=force off
    frameskipon as integer=0
    frameskip as integer=0
    frameskipcounter as integer=0
    texturescale2x as integer=-1
    screensaverpoketime as integer=0
    debugfps as integer=0
    suspendscreensaver as integer=1
	windowmanager as integer=0
end type
dim shared myscreen as screeninfotype

dim shared osgl_ended as integer=0
dim shared osgl_framedrawn as integer=0
dim shared osgl_credits as integer=0

function osgl_fadein_complete as integer
if myscreen.fadeinalpha>0 then function=0 else function=1
end function

sub osgl_popup(byval title as string,byval message as string)
dim i as integer=-1
dim as integer windowxid
ScreenControl 2, windowxid
#macro kdialog()
	if i=-1 then i=exec2("kdialog","--title "+chr$(34)+title+chr$(34)+" --embed "+str(windowxid)+" --msgbox "+chr$(34)+message+chr$(34)+" 0 0")
#endmacro
#macro zenity()
	if i=-1 then i=exec2("zenity","--title "+chr$(34)+title+chr$(34)+" --msgbox "+chr$(34)+message+chr$(34)+" 0 0")
#endmacro
#IFDEF __FB_LINUX__
	if myscreen.windowmanager=1 then
		kdialog()
		zenity()
	else
		zenity()
		kdialog()
	end if
	if i=-1 then i=exec2("gdialog","--title "+chr$(34)+title+chr$(34)+" --msgbox "+chr$(34)+message+chr$(34)+" 0 0")
	if i=-1 then i=exec2("Xdialog","--title "+chr$(34)+title+chr$(34)+" --msgbox "+chr$(34)+message+chr$(34)+" 0 0")
	if i=-1 then printconsole title + " : " + message
#ENDIF

#IFDEF __FB_WIN32__
	Dim hndl As Any Ptr
	hndl=DYLIBLOAD("USER32.DLL")
	if hndl<>0 then
		Dim MessageBoxA As Function ( Byval operand1 As Integer, byval title as string,byval message as string,Byval operand2 As Integer ) As Integer
		MessageBoxA = dylibsymbol( hndl, "MessageBoxA" )
		if MessageBoxA<>0 then
            'MessageBoxA (0, message, title, 0)
			'MessageBoxA (windowxid, message, title, 0)
			MessageBoxA (windowxid, message, title, &h1000 or &h40)
		end if
		dylibfree hndl
	end if
	'print title + " : " + message
	'winpopup
#ENDIF

#IFDEF __FB_DOS__
   	print title + " : " + message
#ENDIF

end sub

function osgl_yesno(byval title as string,byval message as string) as integer
dim i as integer=-1
dim as integer windowxid
ScreenControl 2, windowxid
#macro kdialog()
	if i=-1 then i=exec2("kdialog","--title "+chr$(34)+title+chr$(34)+" --embed "+str(windowxid)+" --yesno "+chr$(34)+message+chr$(34)+" 0 0")
#endmacro
#macro zenity()
	if i=-1 then i=exec2("zenity","--title "+chr$(34)+title+chr$(34)+" --question --text "+chr$(34)+message+chr$(34)+" 0 0")
#endmacro

#IFDEF __FB_LINUX__
	if myscreen.windowmanager=1 then
		kdialog()
		zenity()
	else
		zenity()
		kdialog()
	end if
	if i=-1 then i=exec2("gdialog","--title "+chr$(34)+title+chr$(34)+" --question --text "+chr$(34)+message+chr$(34)+" 0 0")
	if i=-1 then i=exec2("Xdialog","--title "+chr$(34)+title+chr$(34)+" --yesno "+chr$(34)+message+chr$(34)+" 0 0")
	if i=-1 then printconsole title + " : " + message + " : Could not open dialog." : function=0 : exit function
	if i=0 then function=1 : exit function
#ENDIF

#IFDEF __FB_WIN32__
	dim as integer result
	Dim hndl As Any Ptr
	hndl=DYLIBLOAD("USER32.DLL")
	if hndl<>0 then
		Dim MessageBoxA As Function ( Byval operand1 As Integer, byval title as string,byval message as string,Byval operand2 As Integer ) As Integer
		MessageBoxA = dylibsymbol( hndl, "MessageBoxA" )
		if MessageBoxA<>0 then
            'MessageBoxA (0, message, title, 0)
			result=MessageBoxA (windowxid, message, title, &h04 or &h20 or &h1000)
		end if
		dylibfree hndl
	end if
	if result=6 then function=1 : exit function
	'print title + " : " + message
	'winpopup
#ENDIF

#IFDEF __FB_DOS__
   	print title + " : " + message
#ENDIF

function=0
end function


const _osgl_mousetimeout as integer=240

#ifdef _osgl_debugfps_
	myscreen.debugfps=1
#endif

#define osgl_framesdrawn myscreen.framesdrawn

declare function osgl_ScreenSupported(Byval ScreenWidth As Integer,Byval ScreenHeight As Integer,Byval Colour As uInteger) As Integer
declare sub osgl_setvsync(byval value as integer)
declare sub osgl_set3dscreen()
'declare sub glQuad3D (byval x1 as single=0,byval y1 as single=0,byval z1 as single=1,byval x2 as single=1,byval y2 as single=0,byval z2 as single=1,byval x3 as single=0,byval y3 as single=1,byval z3 as single=1,byval x4 as single=1,byval y4 as single=1,byval z4 as single=1,_
'			byval tx1 as single=0, byval ty1 as single=0, byval tx2 as single=1, byval ty2 as single=0, byval tx3 as single=0, byval ty3 as single=1, byval tx4 as single=1, byval ty4 as single=1)
declare sub osgl_cls(byval r as ubyte=0,byval g as ubyte=0,byval b as ubyte=0,byval a as ubyte=255)
declare sub osgl_sync(byval forceframe as integer=0)
declare sub osgl_initaudio()
declare function StringFromList(list as string,byval index as integer,separator as string) as string
declare function homedir() as string
declare sub osgl_createshortcut()
declare sub osgl_collisioneditor()
declare sub osgl_mapeditor(byval filename as string)
declare sub osgl_PAKtool()
declare sub osgl_flc2png()
declare sub osgl_savefont()
declare sub osgl_clear()
declare sub osgl_end()
declare sub osgl_syncbuffers()
declare Function osgl_LoadString(byval filename As String) As String
'#define LoadString osgl_LoadString
declare Function osgl_FreeTexture As integer
declare Function INIGetString(byval stringbuffer as string,byval section as string="CONFIG",byval variable as string,byval vardefault as string="default") as string

dim shared as string osgl_inifile_ : osgl_inifile_=exepath()+"/"+appname+".conf"

#ifndef __FB_WIN32__
if dir(osgl_inifile_)="" then
if exepath()="/usr/bin" or exepath()="/usr/games" then
	osgl_inifile_="/usr/share/"+appname+"/"+appname+".conf"
end if
end if
#endif

#if defined(__FB_WIN32__) or defined(__FB_DOS__)
	#define osgl_username environ("USERNAME")
	#define osgl_homedir environ("USERPROFILE")+"\"
	#define osgl_tempdir environ("TEMP")+"\"
	#define osgl_appsavedir environ("APPDATA")+"\"+appname+"-save\"
	'#define osgl_appdefaultinstalldir environ("PROGRAMFILES")+"\"+appname+"\"
	'#define osgl_appdefaultinstalldir environ("PROGRAMDATA")+"\"+appname+"\"
	'#define osgl_appdefaultinstalldir environ("USERPROFILE")+"\"+appname+"\"
	#define osgl_tempdir environ("TEMP")+"\"
	#define osgl_apptempdir osgl_tempdir+appname+"-temp\"
	#define osgl_barra "\"
	#define osgl_exeextension ".exe"
	#define osgl_exefile exepath+"\"+returnappname+osgl_exeextension
	'#define osgl_apptempdir "l:\tmp\"
#else
	#define osgl_username environ("USER")
	#define osgl_homedir environ("HOME")+"/"
	#define osgl_tempdir "/tmp"+"/"
	#define osgl_appsavedir osgl_homedir+"."+appname+"-save/"
	'#define osgl_appdefaultinstalldir environ("HOME")+"/"+appname+"/"
	#define osgl_apptempdir osgl_tempdir+"."+appname+"-temp/"
	#define osgl_barra "/"
	#define osgl_exeextension ""
	#define osgl_exefile exepath+"/"+returnappname
#endif

function osgl_appdefaultinstalldir as string
#ifdef __FB_WIN32__
if osgl_windowsversion<6 then
	'até o XP
	function=environ("PROGRAMFILES")+"\"+appname+"\"
else
	'Vista pra frente
	'function=environ("USERPROFILE")+"\"+appname+"\"
	function=environ("PROGRAMDATA")+"\"+appname+"\"
end if
#else
	'linux e etc
	function=environ("HOME")+"/"+appname+"/"
#endif
end function


#macro osgl_wrap(value,lower,upper)
	while value>(upper) : value-=((upper)-(lower)+1) : wend
	while value<(lower) : value+=((upper)-(lower)+1) : wend
#endmacro

#macro osgl_range(value,lower,upper)
	if value>upper then
		value=upper
	else
		if value<lower then value=lower
	end if
#endmacro


'player input
#ifndef osgl_maxplayer
    #define osgl_maxplayer 4
#endif

#ifndef osgl_maxbutton
    #define osgl_maxbutton 32
#endif

#ifndef osgl_maxaxis
    #define osgl_maxaxis 16
#endif

dim shared as integer _osgl_joyrumble=1

dim shared as integer _osgl_usemouse=1

dim shared as integer _osgl_numberofjoy=0

type playerinputtype
    usekeyboard as integer
    usegamepad as integer

	pausebutton as integer
	cancelbutton as integer

    devicename as string

    devicefile as string
    eventfile as string
	hasff as integer

    jaxisdefinition(osgl_maxaxis*2) as integer
    jbuttondefinition(osgl_maxbutton) as integer

    kaxisdefinition(osgl_maxaxis*2) as integer
    kbuttondefinition(osgl_maxbutton) as integer

    kreadaxis(osgl_maxaxis) as single
    kreadbutton(osgl_maxbutton) as integer

    jreadaxis(osgl_maxaxis) as single
    jreadbutton as integer

    axis(osgl_maxaxis) as single
    button(osgl_maxbutton) as integer
    oldbutton(osgl_maxbutton) as integer
end type

dim shared osgl_playerinput() as playerinputtype

dim Shared osgl_specialmovebuffer() As String*20

dim shared playerinputstarted as integer =0
dim shared usespecialmoves as integer =1
dim shared osgl_numberofplayers as integer =osgl_maxplayer
dim shared osgl_numberofbuttons as integer =osgl_maxbutton
dim shared osgl_numberofaxis as integer =osgl_maxaxis
dim shared osgl_gamepadsdisabled as integer =0

#define osgl_esckey (multikey(1)<>0)
#define osgl_enterkey (multikey(28)<>0)
#define osgl_spacekey (multikey(&h39)<>0)
#define osgl_delkey (multikey(&h53)<>0)
#define osgl_upkey (multikey(&h48)<>0)
#define osgl_downkey (multikey(&h50)<>0)


function osgl_axis(byval player as integer=1,byval axis as integer=1,byval deadzone as single=.001) as double
    osgl_range(player,1,osgl_maxplayer)
    osgl_range(axis,1,osgl_maxaxis)
    if abs(osgl_playerinput(player).axis(axis))>deadzone then return osgl_playerinput(player).axis(axis)
end function

function osgl_axisdir(byval player as integer=1,byval deadzone as single=.001) as integer
    osgl_range(player,1,osgl_maxplayer)
    Select Case osgl_playerinput(player).axis(1)
        Case Is<-deadzone
            Select Case osgl_playerinput(player).axis(2)
                Case Is <-.deadzone: Return 8
                Case Is >.deadzone:  Return 6
                Case Else:    Return 7
            End select
        Case Is>deadzone
            Select Case osgl_playerinput(player).axis(2)
                Case Is <-.deadzone: Return 2
                Case Is >.deadzone:  Return 4
                Case Else:    Return 3
            End Select
        Case Else
            Select Case osgl_playerinput(player).axis(2)
                Case Is <-deadzone: Return 1
                Case Is >deadzone:  Return 5
                Case Else:    Return 0
            End Select
    End Select
end function


function osgl_button(byval player as integer=1,byval button as integer=-1) as integer
    osgl_range(player,1,osgl_maxplayer)
    'se não informar o botão, retorna qualquer botão (-1)
    if button=-1 then
		dim i as integer=0
        for i=1 to osgl_maxbutton
			'if osgl_playerinput(player).pausebutton<>i then 'não informa pause button
				if osgl_playerinput(player).button(i) then function=osgl_playerinput(player).button(i) : exit function
			'end if
        next i
    end if
    osgl_range(button,1,osgl_maxbutton)
    function=osgl_playerinput(player).button(button)
'	printconsole str(osgl_playerinput(player).button(button))+" p"+str(player)+" b"+str(button)
end function


function osgl_pausebutton(byval player as integer=-999) as integer
dim as integer outs=0
if player=-999 then
	for j as integer=1 to osgl_numberofplayers
		if osgl_playerinput(j).usegamepad then
			if outs=0 then outs=osgl_button(j, osgl_playerinput(j).pausebutton)
		end if
	next j
else
	outs=osgl_button(player, osgl_playerinput(player).pausebutton)
end if
function=outs
end function


function osgl_cancelbutton(byval player as integer=-999) as integer
dim as integer outs=0
if player=-999 then
	for j as integer=1 to osgl_numberofplayers
		if osgl_playerinput(j).usegamepad then
			if outs=0 then outs=osgl_button(j, osgl_playerinput(j).cancelbutton)
		end if
	next j
else
	outs=osgl_button(player, osgl_playerinput(player).cancelbutton)
end if
function=outs
end function


function osgl_scancode(keyname as string) as integer
dim o as integer
keyname=UCase(keyname)
Select case keyname
Case "~","`" : o= 41
Case "ESC" : o= 1
Case "1" : o= 2
Case "2" : o= 3
Case "3" : o = 4
Case "4" : o = 5
Case "5" : o = 6
Case "6" : o = 7
Case "7" : o = 8
Case "8" : o = 9
Case "9" : o = 10
Case "0" : o = 11
Case "-","_" : o = 12
Case "+","=" : o = 13
Case "\","|" : o = 43
Case "BACKSPACE" : o = 14
Case "TAB" : o = 15
Case "CAPSLOCK","CAPS" : o = 58
Case "SHIFT","LSHIFT" : o = 42
Case "CONTROL","LCONTROL","LCTRL" : o = 29
Case "ALT","LALT" : o = 56
Case "SPACE"," " : o = 57
Case "RALT" : o = 184
Case "RCTRL","RCONTROL" : o = 157
Case "RSHIFT" : o = 54
Case "ENTER" : o = 28
Case "Q" : o = 16
Case "W" : o = 17
Case "E" : o = 18
Case "R" : o = 19
Case "T" : o = 20
Case "Y" : o = 21
Case "U" : o = 22
Case "I" : o = 23
Case "O" : o = 24
Case "P" : o = 25
Case "[","{ " : o = 26
Case "]","}" : o = 27
Case "A" : o = 30
Case "S" : o = 31
Case "D" : o = 32
Case "F" : o = 33
Case "G" : o = 34
Case "H" : o = 35
Case "J" : o = 36
Case "K" : o = 37
Case "L" : o = 38
Case ":",";" : o = 39
Case Chr(34),"'" : o = 40
Case "Z" : o = 44
Case "X" : o = 45
Case "C" : o = 46
Case "V" : o = 47
Case "B" : o = 48
Case "N" : o = 49
Case "M" : o = 50
Case "<","," : o = 51
Case ">","." : o = 52
Case "?","/" : o = 53
Case "F1" : o = 59
Case "F2" : o = 60
Case "F3" : o = 61
Case "F4" : o = 62
Case "F5" : o = 63
Case "F6" : o = 64
Case "F7" : o = 65
Case "F8" : o = 66
Case "F9" : o = 67
Case "F10" : o = 68
Case "F11" : o = 87
Case "F12" : o = 88
Case "INSERT","INS": o = 210
Case "DELETE","DEL" : o = 211
Case "HOME" : o = 199
Case "END" : o = 207
Case "PGUP" : o = 201
Case "PAGEUP" : o = 201
Case "PGDOWN","PAGEDOWN" : o = 209
Case "LEFT" : o = &h4B
Case "RIGHT" : o = &h4D
Case "UP" : o = &h48
Case "DOWN" : o = &h50
Case "NUMLOCK","NUM LOCK" : o = 69
Case "NUM/" : o = 181
Case "NUM*" : o = 55
Case "NUM-" : o = 74
Case "NUM7" : o = 71
Case "NUM8" : o = 72
Case "NUM9" : o = 73
Case "NUM4" : o = 75
Case "NUM5" : o = 76
Case "NUM6" : o = 77
Case "NUM1" : o = 79
Case "NUM2" : o = 80
Case "NUM3" : o = 81
Case "NUMINS","NUMINSERT" : o = 82
Case "NUM+" : o= 78
Case "NUMENTER" : o = 156
case else:o=0
End Select
Return o
End function



#macro _getpjoyname(jnum)
scope
if osgl_playerinput(jnum).usegamepad<>0 then
    #ifdef __FB_LINUX__
		osgl_playerinput(jnum).devicefile="/dev/input/js"+str(osgl_playerinput(jnum).usegamepad-1)
		osgl_playerinput(jnum).eventfile="/dev/input/"+dir("/sys/class/input/js"+str(osgl_playerinput(jnum).usegamepad-1)+"/device/event*",&h01 or &h02 or &h04 or &h10 or &h20)
        '/sys/class/input/jsX/device/name
        getjoyname="/sys/class/input/js"+str(osgl_playerinput(jnum).usegamepad-1)+"/device/name"
        if dir(getjoyname)<>"" then osgl_playerinput(jnum).devicename=trim(osgl_LoadString(getjoyname), any " "+chr(13,10,0))
        '/sys/class/input/jsX/device/input:inputX
		'ls /sys/class/input/js0/device/event* -d
        if osgl_playerinput(jnum).devicename="" then
            getjoyname=dir("/sys/class/input/js"+str(osgl_playerinput(jnum).usegamepad-1)+"/device/input:input*",63)
            getjoyname="/sys/class/input/js"+str(osgl_playerinput(jnum).usegamepad-1)+"/device/"+getjoyname+"/name"
            if dir(getjoyname)<>"" then osgl_playerinput(jnum).devicename=trim(osgl_LoadString(getjoyname), any " "+chr(13,10,0))
        end if

		dim as integer fftestfile=freefile2()

		dim as integer fftest=0

		open "/sys/class/input/"+(dir("/sys/class/input/js"+str(osgl_playerinput(jnum).usegamepad-1)+"/device/event*",&h01 or &h02 or &h04 or &h10 or &h20))+"/device/capabilities/ff" for input as #fftestfile
		printdebug "FILE OPEN: #"+str(fftestfile)

		input #fftestfile,fftest

		close #fftestfile
		printdebug "FILE CLOSED: #"+str(fftestfile)

		if fftest<>0 then osgl_playerinput(jnum).hasff=1
		if _osgl_joyrumble=0 then
			osgl_playerinput(jnum).hasff=0
			printdebug "Input : Rumble is disabled."
		end if

    #endif

    #ifdef __FB_WIN32__TODO
	const MAXPNAMELEN = 32
	const MAX_JOYSTICKOEMVXDNAME = 260

		type joy_caps
			wMid as short
			wPid as short
			szPname as string*(MAXPNAMELEN-1)
			wXmin as integer
			wXmax as integer
			wYmin as integer
			wYmax as integer
			wZmin as integer
			wZmax as integer
			wNumButtons as integer
			wPeriodMin as integer
			wPeriodMax as integer
			wRmin as integer
			wRmax as integer
			wUmin as integer
			wUmax as integer
			wVmin as integer
			wVmax as integer
			wCaps as integer
			wMaxAxes as integer
			wNumAxes as integer
			wMaxButtons as integer
			szRegKey as string*(MAXPNAMELEN-1)
			szOEMVxD as string*(MAX_JOYSTICKOEMVXDNAME-1)
		End type
		dim joy_info as joy_caps
		dim joyGetDevCaps as function cdecl(byval as uinteger, byval as joy_caps, byval as uinteger) as uinteger

		joyGetDevCaps(osgl_playerinput(jnum).usegamepad,@joy_info,SizeOf(joy_caps))



	'RegistryGet(HKEY_CLASSES_ROOT,"http\shell\open\command", "", @RegVal)
	'alo.s=ReadRegKey(#HKEY_LOCAL_MACHINE,"System\CurrentControlSet\Control\MediaResources\joystick\"+joy_regkey(a)+"\CurrentJoystickSettings","Joystick"+Str(a+1)+"OEMName")
      'If alo<>"" And alo<>"ERROR"
       ' out.s=ReadRegKey(#HKEY_LOCAL_MACHINE,"System\CurrentControlSet\Control\MediaProperties\PrivateProperties\Joystick\OEM\"+alo.s,"OEMName")
      'EndIf
      'If out.s="" Or out.s="ERROR"
      '  out.s=joy_winmm_name(a)
     ' EndIf
      'joy_name(a)=out.s
	'RegistryGet(HKEY_LOCAL_MACHINE,"", "", @RegVal)
    #endif

    'SDL get joy name
	if libsdl then
		if SDL_JoystickName then
		if osgl_playerinput(jnum).devicename="" then
			osgl_playerinput(jnum).devicename=*SDL_JoystickName(osgl_playerinput(jnum).usegamepad-1)
		end if
		end if
	end if


    'fallback get joy name
    if trim(osgl_playerinput(jnum).devicename)="" then osgl_playerinput(jnum).devicename="Unknown Joystick"
        printconsole "Input: Player "+str(jnum)+" > Joystick "+str(osgl_playerinput(jnum).usegamepad)+" : "+osgl_playerinput(jnum).devicename
    #ifdef __FB_LINUX__
		dim as string ffanswer="No"
		if osgl_playerinput(jnum).hasff then ffanswer="Yes"
		printconsole "Input: "+osgl_playerinput(jnum).devicefile+"  Event: "+osgl_playerinput(jnum).eventfile+"  ForceFeedback: "+ffanswer
	#endif
else
    printconsole "Input: Player "+str(jnum)+" > Keyboard"
end if
end scope
#endmacro




sub osgl_pollmouse()
myscreen.mousexold=myscreen.mousex
myscreen.mouseyold=myscreen.mousey
myscreen.mousezold=myscreen.mousez
if _osgl_usemouse then
	getmouse myscreen.mousex,myscreen.mousey,myscreen.mousez,myscreen.mousebuttons,myscreen.mouseclip
else
	myscreen.mouseclip=1
end if
'printdebug "H "+str(myscreen.mousex)+","+str(myscreen.mousey)
myscreen.mousex=(myscreen.mousex-myscreen.realx/2)/myscreen.ratiox
myscreen.mousey=(-myscreen.mousey+myscreen.realy/2)/myscreen.ratioy
'printdebug "O "+str(myscreen.mousex)+","+str(myscreen.mousey)

if myscreen.mouseclip or myscreen.mousebuttons=0 then
	myscreen.mousebuttons=0
	for j as integer=-1 to ubound(myscreen.mousebtn)
		myscreen.mousebtn(j)=0
	next j
else
	for j as integer=1 to ubound(myscreen.mousebtn)
		if bit(myscreen.mousebuttons,j-1) then
			if myscreen.mousebtn(j)=0 then myscreen.mousebtn(j)=1: myscreen.mousebtn(-1)=1
		end if
	next j
end if

if myscreen.mousetouchscreen then
	if myscreen.mousebuttons=0 then
		myscreen.mouseinactive+=10
		osgl_range(myscreen.mouseinactive,0,_osgl_mousetimeout)
	else
		myscreen.mouseinactive=0
	end if
else
	if myscreen.mousex=myscreen.mousexold and myscreen.mousey=myscreen.mouseyold and myscreen.mousebuttons=0 then
		myscreen.mouseinactive+=1
		osgl_range(myscreen.mouseinactive,0,_osgl_mousetimeout)
	else
		myscreen.mouseinactive=0
	end if
end if

if myscreen.mouseclip then myscreen.mousez=myscreen.mousezold

if myscreen.mouseinactive>=_osgl_mousetimeout then myscreen.mouseclip=1

end sub






sub osgl_initinput(byref numberofplayers as integer =osgl_maxplayer,byref numberofbuttons as integer =osgl_maxbutton,byref numberofaxis as integer =osgl_maxaxis)
if playerinputstarted then
	printdebug "Input : Already started. Aborting."
	exit sub
end if
redim osgl_playerinput(1 to osgl_maxplayer) as playerinputtype
redim osgl_specialmovebuffer(1 To osgl_maxplayer) As String*20

'nomes dos joysticks no Linux:
'cat /sys/class/input/js0/device/name

'nomes dos joysticks no windows : usar código do multijoy
dim getjoyname as string

playerinputstarted=1

dim i as integer=0
dim j1 as integer=0

_osgl_numberofjoy=0

'seta defaults
if osgl_gamepadsdisabled=0 then

for j1=1 to numberofplayers
    osgl_playerinput(j1).usegamepad=j1
	osgl_playerinput(j1).pausebutton=9
	osgl_playerinput(j1).cancelbutton=2
    if Getjoystick (osgl_playerinput(j1).usegamepad-1, osgl_playerinput(j1).jreadbutton,osgl_playerinput(j1).jreadaxis(0),osgl_playerinput(j1).jreadaxis(1),osgl_playerinput(j1).jreadaxis(2),osgl_playerinput(j1).jreadaxis(3),osgl_playerinput(j1).jreadaxis(4),osgl_playerinput(j1).jreadaxis(5),osgl_playerinput(j1).jreadaxis(6),osgl_playerinput(j1).jreadaxis(7))<>0 then
        osgl_playerinput(j1).usegamepad=0
		osgl_playerinput(j1).devicename="Keyboard "+str(j1)
    else
		_osgl_numberofjoy+=1
        for i=1 to osgl_maxbutton
            osgl_playerinput(j1).jbuttondefinition(i)=i
        next i
        for i=1 to osgl_maxaxis
            osgl_playerinput(j1).jaxisdefinition(i)=i
        next i
    end if


_getpjoyname(j1)

printdebug "Input: got name of joystick "+str(j1)

next j1
end if


printconsole "Input: "+str(_osgl_numberofjoy)+" joystick(s) detected."

osgl_playerinput(1).usekeyboard=1
for i=1 to 3
    osgl_playerinput(1).kbuttondefinition(i)=i+50
    osgl_playerinput(1).kbuttondefinition(i+3)=i+37
next i
osgl_playerinput(1).kaxisdefinition(1)=&h4B
osgl_playerinput(1).kaxisdefinition(2)=&h4D
osgl_playerinput(1).kaxisdefinition(3)=&h48
osgl_playerinput(1).kaxisdefinition(4)=&h50

if numberofplayers>1 then
    osgl_playerinput(2).usekeyboard=1
    for i=1 to 3
        osgl_playerinput(2).kbuttondefinition(i)=i+43
        'osgl_playerinput(2).kbuttondefinition(i+3)=i+32
    next i
    osgl_playerinput(2).kaxisdefinition(1)=30
    osgl_playerinput(2).kaxisdefinition(2)=32
    osgl_playerinput(2).kaxisdefinition(3)=17
    osgl_playerinput(2).kaxisdefinition(4)=31
end if

'le do INI input ini
dim as string inifile=osgl_inifile_
dim as string inidata=""
if dir(inifile)<>"" then
	inidata=osgl_LoadString(inifile)
	printconsole "Input : Loading settings from "+inifile

    if inidata<>"" then
		for j1=1 to numberofplayers
			'joy
			osgl_playerinput(j1).usegamepad=val(INIGetString(inidata,"P"+str(j1)+"INPUT","usegamepad",str(j1)))
			if osgl_playerinput(j1).usegamepad then
				if Getjoystick (osgl_playerinput(j1).usegamepad-1, osgl_playerinput(j1).jreadbutton,osgl_playerinput(j1).jreadaxis(0),osgl_playerinput(j1).jreadaxis(1),osgl_playerinput(j1).jreadaxis(2),osgl_playerinput(j1).jreadaxis(3),osgl_playerinput(j1).jreadaxis(4),osgl_playerinput(j1).jreadaxis(5),osgl_playerinput(j1).jreadaxis(6),osgl_playerinput(j1).jreadaxis(7))<>0 then
					'nao detectado
					osgl_playerinput(j1).usegamepad=0
					osgl_playerinput(j1).devicename="Keyboard "+str(j1)
				else
					_getpjoyname(j1)
					for i as integer=1 to osgl_maxbutton
						osgl_playerinput(j1).jbuttondefinition(i)=val(INIGetString(inidata,"P"+str(j1)+"INPUT","jbutton"+str(i),str(i)))
					next i
					for i as integer=1 to osgl_maxaxis
						osgl_playerinput(j1).jaxisdefinition(i)=val(INIGetString(inidata,"P"+str(j1)+"INPUT","jaxis"+str(i),str(i)))
					next i
					osgl_playerinput(j1).pausebutton=val(INIGetString(inidata,"P"+str(j1)+"INPUT","pausebutton","9"))
					osgl_playerinput(j1).cancelbutton=val(INIGetString(inidata,"P"+str(j1)+"INPUT","cancelbutton","2"))
					if osgl_playerinput(j1).pausebutton<1 then osgl_playerinput(j1).pausebutton=9
					if osgl_playerinput(j1).cancelbutton<1 then osgl_playerinput(j1).cancelbutton=2
				end if
			end if

			'key

			osgl_playerinput(j1).usekeyboard=val(INIGetString(inidata,"P"+str(j1)+"INPUT","usekeyboard",str(osgl_playerinput(j1).usekeyboard)))

			dim as string aa=""

			for i as integer=1 to osgl_maxbutton
				aa=INIGetString(inidata,"P"+str(j1)+"INPUT","button"+str(i),"none")
				if aa<>"none" then osgl_playerinput(j1).kbuttondefinition(i)=osgl_scancode(aa)
			next i

			aa=INIGetString(inidata,"P"+str(j1)+"INPUT","left","none")
			if aa<>"none" then osgl_playerinput(j1).kaxisdefinition(1)=osgl_scancode(aa)

			aa=INIGetString(inidata,"P"+str(j1)+"INPUT","right","none")
			if aa<>"none" then osgl_playerinput(j1).kaxisdefinition(2)=osgl_scancode(aa)

			aa=INIGetString(inidata,"P"+str(j1)+"INPUT","up","none")
			if aa<>"none" then osgl_playerinput(j1).kaxisdefinition(3)=osgl_scancode(aa)

			aa=INIGetString(inidata,"P"+str(j1)+"INPUT","down","none")
			if aa<>"none" then osgl_playerinput(j1).kaxisdefinition(4)=osgl_scancode(aa)

		next j1
	end if
end if

'testa joystick
'if gamepadsdisabled=0 then
'  for j=0 to numberofplayers
'    if osgl_playerinput(j1).usegamepad then
'        if Getjoystick (osgl_playerinput(j1).usegamepad-1, osgl_playerinput(j1).jreadbutton,osgl_playerinput(j1).jreadaxis(0),osgl_playerinput(j1).jreadaxis(1),osgl_playerinput(j1).jreadaxis(2),osgl_playerinput(j1).jreadaxis(3),osgl_playerinput(j1).jreadaxis(4),osgl_playerinput(j1).jreadaxis(5),osgl_playerinput(j1).jreadaxis(6),osgl_playerinput(j1).jreadaxis(7))<>0 then
'            osgl_playerinput(j1).usegamepad=0
'            osgl_playerinput(j1).jreadbutton=0
'               for i=0 to 7
'                osgl_playerinput(j1).jreadaxis(i)=0
'            next i
'        else
'            for i=7 to 0 step -1
'                if osgl_playerinput(j1).jreadaxis(i)<-2 then osgl_playerinput(j1).jreadaxis(i)=0
'            next i
'         end if
'    end if
'    next j
'end if

osgl_pollmouse()

end sub

 'poll OS events
#define osgl_pollosevents screencontrol 200

'POLL_____________________________________________________
sub osgl_pollinput_keyboard()
'I had to separate this because multikey will leak memory if used in a thread
'teclado

dim i as integer=0
dim j as integer=0

for j=1 to osgl_numberofplayers
if osgl_playerinput(j).usekeyboard then
    for i=1 to osgl_numberofaxis
    'this may be the cause of the FREEZES (sucks!!!)
    'trying to access out of array limits????
        'if (2*i)<= then
    if osgl_playerinput(j).kaxisdefinition(2*i-1) then
		'multikey causes a memory leak on multi-threading
            osgl_playerinput(j).kreadaxis(i)=(multikey(osgl_playerinput(j).kaxisdefinition(2*i-1))<>0)-(multikey(osgl_playerinput(j).kaxisdefinition(2*i))<>0)
        end if
    'end if
    next i
    for i=1 to osgl_numberofbuttons
        if osgl_playerinput(j).kbuttondefinition(i) then
		'multikey causes a memory leak on multi-threading
            osgl_playerinput(j).kreadbutton(i)=multikey(osgl_playerinput(j).kbuttondefinition(i))
        end if
    next i
	if j=1 then
		if osgl_playerinput(1).kreadbutton(1)=0 then osgl_playerinput(1).kreadbutton(1)=multikey(&h1C) 'ENTER = BOTAO 1 (fixo)
		if osgl_playerinput(1).kreadbutton(2)=0 then osgl_playerinput(1).kreadbutton(2)=multikey(&h53) 'DEL = BOTAO 2 (fixo)
		if osgl_playerinput(1).kreadbutton(3)=0 then osgl_playerinput(1).kreadbutton(3)=multikey(&h39) 'SPACE = BOTAO 3 (fixo)
		if osgl_playerinput(1).cancelbutton=1 then swap osgl_playerinput(1).kreadbutton(1), osgl_playerinput(1).kreadbutton(2) 'inverte botões 1 e 2  se cancel=enter
		if osgl_playerinput(1).cancelbutton=3 then swap osgl_playerinput(1).kreadbutton(3), osgl_playerinput(1).kreadbutton(2) 'inverte botão 2 e 3 se cancel=space
	end if
end if
next j
end sub


sub osgl_pollinput()

if playerinputstarted=0 then
    osgl_initinput(osgl_numberofplayers,osgl_maxbutton,osgl_maxaxis)
    printdebug "Input : Starting..."
end if

dim i as integer=0
dim j as integer=0

'gamepad
if osgl_gamepadsdisabled=0 then
    for j=1 to osgl_numberofplayers
    if osgl_playerinput(j).usegamepad then
        Getjoystick (osgl_playerinput(j).usegamepad-1, osgl_playerinput(j).jreadbutton,osgl_playerinput(j).jreadaxis(1),osgl_playerinput(j).jreadaxis(2),osgl_playerinput(j).jreadaxis(3),osgl_playerinput(j).jreadaxis(4),osgl_playerinput(j).jreadaxis(5),osgl_playerinput(j).jreadaxis(6),osgl_playerinput(j).jreadaxis(7),osgl_playerinput(j).jreadaxis(8))
        for i=8 to 1 step -1
            if osgl_playerinput(j).jreadaxis(i)<-2 then osgl_playerinput(j).jreadaxis(i)=0
        next i
    end if
    next j
end if

'combinar
for j=1 to osgl_numberofplayers
    for i=1 to 8
        osgl_playerinput(j).axis(i)=osgl_playerinput(j).kreadaxis(i)
        if osgl_playerinput(j).usegamepad then
        if osgl_playerinput(j).axis(i)=0 then
            if osgl_playerinput(j).jaxisdefinition(i) then
                osgl_playerinput(j).axis(i)=osgl_playerinput(j).jreadaxis(osgl_playerinput(j).jaxisdefinition(i))
            end if
        end if
        end if
    next i
    for i=1 to osgl_numberofbuttons
        osgl_playerinput(j).oldbutton(i)=osgl_playerinput(j).button(i)
        osgl_playerinput(j).button(i)=-osgl_playerinput(j).kreadbutton(i)
        if osgl_playerinput(j).button(i)=0 then
        if osgl_playerinput(j).usegamepad then
            if osgl_playerinput(j).jbuttondefinition(i) then
                osgl_playerinput(j).button(i)=-bit(osgl_playerinput(j).jreadbutton,osgl_playerinput(j).jbuttondefinition(i)-1)
            end if
        end if
        end if
        'segura botao
        if osgl_playerinput(j).button(i) then
        if osgl_playerinput(j).oldbutton(i) then
            osgl_playerinput(j).button(i)=2
        end if
        end if
    next i
'printdebug "P"+str(j)+" use"+str(osgl_playerinput(j).usegamepad)+" b"+str(osgl_playerinput(j).jreadbutton)+" a"+str(osgl_playerinput(j).jreadaxis(0))
next j

'A single precision value between -1.0 and 1.0 is returned for each valid axis. If the axis does not exist for the controller, a value of -1000.00 is returned.
'printdebug osgl_playerinput(0).axis(2),osgl_playerinput(0).axis(3),osgl_playerinput(0).axis(4),osgl_playerinput(0).axis(5),osgl_playerinput(0).axis(6),osgl_playerinput(0).axis(7)
'poll special moves
' static a As String
' If usespecialmoves Then
'for j=1 to osgl_numberofplayers
'    a=Str(osgl_axisdir(j,))
'    If Mid(osgl_specialmovebuffer(j),1,1)<>a Then osgl_specialmovebuffer(j)=a+osgl_specialmovebuffer(j)
    'printconsole Mid(specialmovebuffer(j),1,1),a,specialmovebuffer(j)
'Next j
'End If
end sub
dim shared as any ptr osgl_pollinput_thread
dim shared as any ptr osgl_pollinput_ptr
osgl_pollinput_ptr=@osgl_pollinput


function osgl_getwindowxid as integer
'get window XID
ScreenControl 2, myscreen.windowxid
if myscreen.windowxid<>0 then printconsole "Screen : Window XID is "+str(myscreen.windowxid) else printconsole "Screen : No window detected"
function=myscreen.windowxid
end function


sub osgl_screensaver(byval enable as integer=1)

#ifdef __FB_LINUX__
if myscreen.windowxid=0 then osgl_getwindowxid
if myscreen.windowxid=0 then exit sub

if enable then

'enable screensaver
printdebug "Screen : resume screensaver"
shell "xset s default +dpms"
shell "dcop kdesktop KScreensaverIface enable true"
shell "xdg-screensaver resume "+str(myscreen.windowxid)

else

'disable screensaver
printdebug "Screen : suspend screensaver"
shell "xset s off -dpms"
shell "dcop kdesktop KScreensaverIface enable false"
shell "xdg-screensaver suspend "+str(myscreen.windowxid)
'shell "gnome-screensaver-command -i -n "+appname+" -r test"  'Command blocks while inhibit is active.
end if

#else

'the windows way
SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, enable, 0, 0)

#endif

end sub


sub osgl_pokescreensaver
#ifdef __FB_LINUX__
    shell "xdg-screensaver reset"
    shell "xscreensaver-command -deactivate"
    shell "qdbus org.freedesktop.ScreenSaver /ScreenSaver SimulateUserActivity"
    shell "gnome-screensaver-command --poke"
#endif
end sub



    #ifdef __FB_WIN32__

    extern "Windows" lib "user32"
      declare function SendEvent alias "SendMessageA" (hWin   as integer, _
                                                       uMsg   as uinteger, _
                                                       wParam as integer, _
                                                       lParam as integer) as integer
    end extern

    #else

    extern "C" lib "X11"
    declare function XOpenDisplay      (byval pName      as zstring ptr=0) as any ptr
    declare function XDefaultRootWindow(byval pDisplay   as any ptr) as integer
    declare function XKeysymToKeycode  (byval pDisplay   as any ptr, byval ks as integer) as ubyte
    declare function XSendEvent        (byval pDisplay   as any ptr, _
                                        byval hWin       as integer , _
                                        byval propagate  as integer , _
                                        byval event_mask as integer , _
                                        byval event_send as any ptr) as integer
    declare function XCloseDisplay(byval pDisplay as any ptr) as integer
    end extern
    sub SendEvent(byval pDisplay   as any ptr , _
                  byval hWin       as integer , _
                  byval bPressed   as integer , _
                  byval iKeycode   as integer)
      dim as integer event(24)
      event( 0) = iif(bPressed,2,3)
      event( 1) = 1
      event( 2) = cint(pDisplay)
      event( 3) = hWin
      event( 4) = XDefaultRootWindow(pDisplay)
      event(11) = 1
      event(13) = XKeysymToKeycode(pDisplay,iKeyCode)
      event(14) = 1
      XSendEvent(pDisplay,hWin,1,event(0)-1,@event(0))
    end sub

    #endif


sub osgl_emulateAltEnter()
      if ScreenPtr()=0 then return
      dim as integer hWin
      ScreenControl 2,hWin
      if hWin=0 then return
    #ifdef __FB_WIN32__
      SendEvent(hWin,260,18,&H20380001) ' DOWN ALT_L
      SendEvent(hWin,260,13,&H201C0001) ' DOWN ENTER
      SendEvent(hWin,261,13,&HE01C0001) ' UP ENTER
      SendEvent(hWin,261,18,&HC0380001) ' UP ALT_L
    #else
      dim as any ptr pDisplay = XOpenDisplay()
      if pDisplay=0 then return
      SendEvent(pDisplay,hWin,1,&HFFE9) ' DOWN ALT_L
      SendEvent(pDisplay,hWin,1,&HFF0D) ' DOWN ENTER
      SendEvent(pDisplay,hWin,0,&HFF0D) ' UP ENTER
      SendEvent(pDisplay,hWin,0,&HFFE9) ' UP ALT_L
      XCloseDisplay pDisplay
    #endif
end sub


sub osgl_emulateAltEnter2()

#ifndef __FB_WIN32__
	shell "xdotool key Alt_L+Return" 'I don't think xdotool is installed by default
#else
	dim ki(0 to 3) as INPUT_
	'' synthesize press of Alt key:
	ki(0).type = INPUT_KEYBOARD
	ki(0).ki.wVk = VK_MENU
	ki(0).ki.dwFlags = 0
	'' synthesize press of Enter key:
	ki(1).type = INPUT_KEYBOARD
	ki(1).ki.wVk = VK_RETURN
	ki(1).ki.dwFlags = 0
	'' synthesize release of Enter key:
	ki(2).type = INPUT_KEYBOARD
	ki(2).ki.wVk = VK_RETURN
	ki(2).ki.dwFlags = KEYEVENTF_KEYUP
	'' synthesize release of Alt key:
	ki(3).type = INPUT_KEYBOARD
	ki(3).ki.wVk = VK_MENU
	ki(3).ki.dwFlags = KEYEVENTF_KEYUP

	SendInput( 4, @ki(0), sizeof(ki) )

#endif

end sub 'osgl_emulateAltEnter()

function osgl_frames2minutes(byval frames as long=-999, byval miliseconds as integer=1) as string
	dim as string outs
	dim as long minut, sec, csec, syncr, syncr2
	if frames=-999 then
		'sem parametro retorna de acordo com o total de frames renderizadas pela engine
		frames=osgl_framesdrawn
	else
		if myscreen.frameskip then frames=frames/2
	end if
	syncr=myscreen.mysyncrate
	if myscreen.mysyncrate=0 then syncr=60
	syncr2=syncr*60
	minut=frames\syncr2
	sec=((frames mod syncr2)\syncr)
	csec=100*((frames mod syncr2) mod syncr)\syncr
	if miliseconds then
		outs=str(minut)+":"+right("0"+str(sec),2)+"."+right("0"+str(csec),2)
	else
		outs=str(minut)+":"+right("0"+str(sec),2)
	end if
	function=outs
end function

'sub osgl_restorescreensaver destructor
'osgl_screensaver 1
'end sub

'declare sub osgl_4(byval style as integer=4, byval savefont as integer=0)
declare function osgl_detectwine() as integer
declare sub osgl_createtexture(byref texture as integer=0, byval x as integer=1, byval y as integer=1)

sub osgl_volume(byval sfxvolume as integer=10,byval musicvolume as integer=10)
osgl_range(sfxvolume,0,10)
osgl_range(musicvolume,0,10)
sound.sfxvolume=sfxvolume*.1
sound.musicvolume=musicvolume*.1
if Mix_VolumeMusic<>0 then Mix_VolumeMusic(128*sound.musicvolume)
end sub

sub String2Array(mystring as string, separator as string=",", stringarray() as string,byval keepseparator as integer=0)
dim getstring as string
dim as integer index=1
do
    getstring=StringFromList(mystring,index,separator)
    if getstring="" then
        exit sub
    else
        redim preserve stringarray(1 to index) as string
        stringarray(index)=left(getstring,len(getstring)-len(separator)+2)
	'if mid(getstring,len(getstring),1)=chr(10) then getstring=left(getstring,len(getstring)-1)
	if keepseparator then stringarray(index)+=separator
        index+=1
    end if
loop
end sub

sub StringToArray_(mystring as string, separator as string=",", stringarray() as string)
dim getstring as string
dim as integer index=1
do
    getstring=StringFromList(mystring,index,separator)
    if getstring="" then
        exit sub
    else
        redim preserve stringarray(1 to index) as string
        stringarray(index)=getstring
        index+=1
    end if
loop
end sub


dim shared as integer ddfmode=0

'SET SCREEN MODE
#macro osgl_setvideomode()
	myscreen.switches=myscreen.fullscreen*&h01 or myscreen.useopengl*&h02 or myscreen.gfxnoswitch*&h04 or myscreen.alphaprimitives*&h40 or myscreen.antialias*&h40000 or myscreen.windownoframe*&h08 or fb.GFX_HIGH_PRIORITY
	screenres myscreen.realx,myscreen.realy,myscreen.depth,myscreen.numpages,myscreen.switches,myscreen.mysyncrate
#endmacro


sub osgl_init(byval wtitle as string="", byval x as const integer=0, byval y as const integer=0,  byval syncrate as integer =60, byval setnumberofplayers as integer=4, byval  realx as integer=0, byval  realy as integer=0, byval depth as integer =32, byval fullscreen as integer =1, byval antialias as integer =0,byval vsync as integer =1,byval useaudio as const integer=1)
if myscreen.started=1 then printconsole "Init : Already started!":exit sub
osgl_numberofplayers=setnumberofplayers

'#ifdef __FB_UNIX__
'    printconsole "Init : Are you unix-like?"
'#endif

'#ifdef __FB_PCOS__
'    printconsole "Init : Are you windows-like?"
'#endif

#ifdef __FB_LINUX__
    printconsole "Init : Hi Linux!!!"
    printconsole "Init : ''Freedom is the most precious thing.''  ;) "
    printconsole "Init : LANG = "+environ("LANG")
    printconsole "Init : LANGUAGE = "+environ("LANGUAGE")
	if exec("pidof","ksmserver")=0 then
		printconsole "Init : Detected KDE"
		myscreen.windowmanager=1
	else
		if exec("pidof","gnome-session")=0 then
			printconsole "Init : Detected GNOME"
			myscreen.windowmanager=2
		else
			if exec("pidof","xfce-mcs-manage")=0 or exec("pidof","xfce4-session")=0 then
				printconsole "Init : Detected XFCE"
				myscreen.windowmanager=3
			else
				if exec("pidof","lxsession")=0 then
					printconsole "Init : Detected LXDE"
					myscreen.windowmanager=4
				else
					printconsole "Init : Could not determine your window manager."
					myscreen.windowmanager=0
				end if
			end if
		end if
	end if
#endif

#ifdef __FB_WIN32__
    printconsole "Init : Hello, Windows..."
	if osgl_detectwine then
		printconsole "Init : Or maybe should I say... Wine?!"
		printconsole "Init : Hey, there is a native version of this application! What are you trying to prove?! :P"
	else
		printconsole "Init : Did you know you can get a fast, stable and secure operating system for free?"
		printconsole "Init : Check http://www.ubuntu.com , http://www.linuxhq.org or http://www.distrowatch.com"
	end if
	myscreen.windowmanager=0
    'printdebug str(dir("z:\usr\bin\wine"))
    'if dir("z:\usr\bin\wine")<>"" then
		'printdebug "Init : Or maybe should I say Wine?!"
	'end if
#endif

#ifdef __FB_DOS__
	printconsole "Init : Hi DOS!!!"
	printconsole "Init : This is totally unsupported!!!"
	myscreen.windowmanager=0
#endif

osgl_clear()

printdebug "Init : Starting program..."

printconsole "Init : Current directory is : curdir = "+curdir
printconsole "Init : Executable directory is : exepath = "+exepath
printconsole "Init : Home directory is : homedir = "+homedir

'Load configuration file

dim as string inidata=""
dim as string inifile="" : inifile=osgl_inifile_

printconsole "Init : Configuration file is = "+inifile

if dir(inifile)<>"" then inidata=osgl_LoadString(inifile)
printconsole "Init : Loading settings from "+inifile
if inidata<>"" then
    dim getscreenres as string=lcase(INIGetString(inidata,"CONFIG","resolution",""))

	if instr(getscreenres,"x") then 'se tiver x, seta resolução. se não tiver, é auto
		#ifdef _osgl_xscreen_
			realx=_osgl_xscreen_
		#else
			realx=val(StringFromList(getscreenres,1,"x"))
		#endif

		#ifdef _osgl_yscreen_
			realy=_osgl_yscreen_
		#else
			realy=val(StringFromList(getscreenres,2,"x"))
		#endif
	end if

    'myscreen.widescreenpixels=val(INIGetString(inidata,"CONFIG","widescreenpixels","0"))
    select case lcase(INIGetString(inidata,"CONFIG","widescreen","wide"))
		case "0","no","off","disabled","disable","4:3" : myscreen.widescreen=0 : myscreen.blackborders=0
		case "fake","fakewide" : myscreen.widescreen=1 : myscreen.blackborders=1
		case else : myscreen.widescreen=1 : myscreen.blackborders=0
	end select

	myscreen.widescreen=val(INIGetString(inidata,"CONFIG","widescreen","1"))

    select case lcase(INIGetString(inidata,"CONFIG","renderer",""))
        case "software","soft":myscreen.useopengl=0
        case "opengl","hardware":myscreen.useopengl=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","fullscreen",""))
        case "0","false","off":fullscreen=0
        case "1","true","on":fullscreen=1
    end select
	#ifdef _osgl_windowed_
		fullscreen=0 : myscreen.fullscreen=0
	#endif
    select case lcase(INIGetString(inidata,"CONFIG","vsync",""))
        case "-1","nochange","dontchange":vsync=-1
        case "0","false","off":vsync=0
        case "1","true","on":vsync=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","3dstereo",""))
        case "0","false","off":myscreen.stereo3d=0
        case "1","true","on":myscreen.stereo3d=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","bgra",""))
        case "0","false","off":myscreen.usebgra=0
        case "1","true","on":myscreen.usebgra=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","usefrontbuffer",""))
        case "0","false","off":myscreen.usefrontbuffer=0
        case "1","true","on":myscreen.usefrontbuffer=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","texturecompression",""))
        case "0","false","off":myscreen.usetexturecompression=0
        case "1","true","on":myscreen.usetexturecompression=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","antialias",""))
        case "0","false","off":antialias=0
        case "1","true","on":antialias=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","rumble",""))
        case "0","false","off":_osgl_joyrumble=0
        case "1","true","on":_osgl_joyrumble=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","mouse",""))
        case "0","false","off":_osgl_usemouse=0
        case "1","true","on":_osgl_usemouse=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","filter",""))
        case "0","false","off":myscreen.filter=0
        case "1","true","on":myscreen.filter=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","console",""))
        case "0","false","off":consoleon=0:debug=0
        case "1","true","on":consoleon=1:debug=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","debug",""))
        case "0","false","off":debug=0
        case "1","true","on":debug=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","audio",""))
        case "0","false","off":osgl_disableaudio()
    end select
    select case lcase(INIGetString(inidata,"CONFIG","sleep",""))
        case "1","true","on":myscreen.cansleep=1
    end select
    select case lcase(INIGetString(inidata,"CONFIG","gfxswitch",""))
        case "1","true","on":myscreen.gfxnoswitch=0
    end select
    select case lcase(INIGetString(inidata,"CONFIG","gamelevel",""))
        case "0","easy":osgl_gamelevel=0
        case "1","normal":osgl_gamelevel=1
        case "2","hard":osgl_gamelevel=2
        case "3","ultimate":osgl_gamelevel=3
    end select
end if
osgl_volume(val(INIGetString(inidata,"CONFIG","sfxvolume","10")),val(INIGetString(inidata,"CONFIG","musicvolume","10")))

select case lcase(INIGetString(inidata,"CONFIG","frameskip","off"))
	case "on", "1" : myscreen.frameskipmode=1:myscreen.frameskipon=1 'force on
	case "auto"	   : myscreen.frameskipmode=0:myscreen.frameskipon=0 'auto
	case else : myscreen.frameskipmode=-1:myscreen.frameskipon=0 'force off
end select



'verifica linha de comando
if command<>"" then
for i as integer=1 to 255
    if lcase(command(i))="-createshortcut" then osgl_createshortcut : osgl_end : end
    if lcase(command(i))="-nospeedlimit" then syncrate=0
    if lcase(command(i))="-window" then fullscreen=0
    if lcase(command(i))="-windownoframe" then myscreen.windownoframe=1 : fullscreen=0
    if lcase(command(i))="-desktopmode" then myscreen.windownoframe=1 : fullscreen=0 : realx=0: realy=0
    if lcase(command(i))="-fullscreen" then fullscreen=1
    if lcase(command(i))="-gfxswitch" then myscreen.gfxnoswitch=0
    if lcase(command(i))="-3dstereo" then myscreen.stereo3d=1
    if lcase(command(i))="-stereo3d" then myscreen.stereo3d=1
    if lcase(command(i))="-anaglyph" then myscreen.stereo3d=1
    if lcase(command(i))="-low" then antialias=0:myscreen.filter=0:vsync=0:myscreen.frameskipmode=1:myscreen.frameskipon=1:myscreen.texturescale2x=0
    if lcase(command(i))="-antialias" then antialias=1
    if lcase(command(i))="-noantialias" then antialias=0
    if lcase(command(i))="-texturescaler" then myscreen.texturescale2x=1
    if lcase(command(i))="-notexturescaler" then myscreen.texturescale2x=0
    if lcase(command(i))="-filter" then myscreen.filter=1
    if lcase(command(i))="-nofilter" then myscreen.filter=0
    if lcase(command(i))="-software" then myscreen.useopengl=0
    if lcase(command(i))="-opengl" then myscreen.useopengl=1
    if lcase(command(i))="-altsync" then myscreen.syncmode=1
    if lcase(command(i))="-altsync1" then myscreen.syncmode=1
    if lcase(command(i))="-altsync2" then myscreen.syncmode=2
    if lcase(command(i))="-normalsync" then myscreen.syncmode=0
    if lcase(command(i))="-nobgra" then myscreen.usebgra=0
    if lcase(command(i))="-bgra" then myscreen.usebgra=1
    if lcase(command(i))="-nofrontbuffer" then myscreen.usefrontbuffer=0
    if lcase(command(i))="-frontbuffer" then myscreen.usefrontbuffer=1
    if lcase(command(i))="-usefrontbuffer" then myscreen.usefrontbuffer=1
    if lcase(command(i))="-notexturecompression" then myscreen.usetexturecompression=0
    if lcase(command(i))="-texturecompression" then myscreen.usetexturecompression=1
    if lcase(command(i))="-compresstextures" then myscreen.usetexturecompression=1
    '1920x1200,1920x1080,1680x1050,1600x1200,1600x1024,1600x900,1440x900,1400x1050,1366x768,1360x800,1280x1024,1280x960,1280x854,1280x800,1280x768,1280x720,1152x864,1152x768,1024x768,1024x600,960x720,960x600,928x696,896x672,840x525,832x624,800x600,800x512,720x576,720x480,640x512,640x480,640x400,400x300
    if lcase(command(i))="-320x200" then realx=320:realy=200
    if lcase(command(i))="-320x240" then realx=320:realy=240
    if lcase(command(i))="-400x300" then realx=400:realy=300
    if lcase(command(i))="-640x400" then realx=640:realy=400
    if lcase(command(i))="-640x480" then realx=640:realy=480
    if lcase(command(i))="-640x512" then realx=640:realy=512
    if lcase(command(i))="-720x480" then realx=720:realy=480
    if lcase(command(i))="-720x576" then realx=720:realy=576
    if lcase(command(i))="-800x480" then realx=800:realy=480
    if lcase(command(i))="-800x512" then realx=800:realy=512
    if lcase(command(i))="-800x600" then realx=800:realy=600
    if lcase(command(i))="-832x624" then realx=832:realy=624
    if lcase(command(i))="-840x525" then realx=840:realy=525
    if lcase(command(i))="-896x672" then realx=896:realy=672
    if lcase(command(i))="-928x696" then realx=928:realy=696
    if lcase(command(i))="-960x600" then realx=960:realy=600
    if lcase(command(i))="-960x720" then realx=960:realy=720
    if lcase(command(i))="-1024x600" then realx=1024:realy=600
    if lcase(command(i))="-1024x768" then realx=1024:realy=768
    if lcase(command(i))="-1152x768" then realx=1152:realy=768
    if lcase(command(i))="-1152x864" then realx=1152:realy=864
    if lcase(command(i))="-1280x720" then realx=1280:realy=720
    if lcase(command(i))="-hdtv" or lcase(command(i))="-hd" then realx=1280:realy=720
    if lcase(command(i))="-1280x768" then realx=1280:realy=768
    if lcase(command(i))="-1280x800" then realx=1280:realy=800
    if lcase(command(i))="-1280x854" then realx=1280:realy=854
    if lcase(command(i))="-1280x960" then realx=1280:realy=960
    if lcase(command(i))="-1280x1024" then realx=1280:realy=1024
    if lcase(command(i))="-1360x768" then realx=1360:realy=768
    if lcase(command(i))="-1360x800" then realx=1360:realy=800
    if lcase(command(i))="-1366x768" then realx=1366:realy=768
    if lcase(command(i))="-1400x1050" then realx=1400:realy=1050
    if lcase(command(i))="-1440x900" then realx=1440:realy=900
    if lcase(command(i))="-1600x900" then realx=1600:realy=900
    if lcase(command(i))="-1600x1024" then realx=1600:realy=1024
    if lcase(command(i))="-1600x1200" then realx=1600:realy=1200
    if lcase(command(i))="-1680x1050" then realx=1680:realy=1050
    if lcase(command(i))="-1920x1080" then realx=1920:realy=1080
    if lcase(command(i))="-1920x1200" then realx=1920:realy=1200
    if lcase(command(i))="-fullhd" then realx=1920:realy=1080
    if lcase(command(i))="-widescreen" or lcase(command(i))= "-wide" then myscreen.widescreen=1 : myscreen.blackborders=0
    if lcase(command(i))="-nowidescreen" or lcase(command(i))= "-nowide"  or lcase(command(i))= "-4:3" then myscreen.widescreen=0  : myscreen.blackborders=0
    if lcase(command(i))="-fakewidescreen" or lcase(command(i))= "-fakewide"  then myscreen.widescreen=1 : myscreen.blackborders=1
    if lcase(command(i))="-debug" then debug=1
    if lcase(command(i))="-nodebug" then debug=0
    if lcase(command(i))="-vsync" then vsync=1
    if lcase(command(i))="-vsyncnochange" then vsync=-1
    if lcase(command(i))="-novsync" or lcase(command(i))="-vsyncoff" then vsync=0
    if lcase(command(i))="-debugfps" or lcase(command(i))="-showfps" then myscreen.debugfps=1
    if lcase(command(i))="-benchmark" then myscreen.debugfps=1 : vsync=0 : syncrate=0
    if lcase(command(i))="-32bpp" then depth=32
    if lcase(command(i))="-24bpp" then depth=24
    if lcase(command(i))="-16bpp" then depth=16
    if lcase(command(i))="-15bpp" then depth=15
    if lcase(command(i))="-8bpp" then depth=8
    if lcase(command(i))="-frameskip" then myscreen.frameskipmode=1:myscreen.frameskipon=1 'force on
    if lcase(command(i))="-noframeskip" then myscreen.frameskipmode=-1:myscreen.frameskipon=0 'force off
    if lcase(command(i))="-autoframeskip" then myscreen.frameskipmode=0:myscreen.frameskipon=0 'auto
    if lcase(command(i))="-sleep" then myscreen.cansleep=1
    if lcase(command(i))="-high" then antialias=1:myscreen.filter=1:vsync=1
	if lcase(command(i))="-rumble" then _osgl_joyrumble=1
	if lcase(command(i))="-norumble" then _osgl_joyrumble=0
    if lcase(command(i))="-suspendscreensaver" then  myscreen.suspendscreensaver=1
    if lcase(command(i))="-dontsuspendscreensaver" or lcase(command(i))="-nosuspendscreensaver" then myscreen.suspendscreensaver=0
    if lcase(command(i))="-resolution" or lcase(command(i))="-res" then
        realx=val(command(i+1)):realy=val(command(i+2))
        exit for
    end if
    if lcase(command(i))="-easy" then osgl_gamelevel=0
    if lcase(command(i))="-normal" then osgl_gamelevel=1
    if lcase(command(i))="-hard" then osgl_gamelevel=2
    if lcase(command(i))="-ultimate" then osgl_gamelevel=3

    if lcase(command(i))= "-help" then
        printconsole
        printconsole "Command line options: "
        printconsole
        printconsole "-fullscreen : Run in fullscreen mode"
        printconsole "-window : Run in windowed mode"
        printconsole "-gfxswitch : Enable ALT+ENTER to switch between window / fullscreen"
        printconsole "-resolution <WIDTH> <HEIGHT> : Set screen resolution / window size"
        printconsole "-antialias : Turn on antialias screen filter"
        printconsole "-noantialias : Turn off antialias screen filter"
        printconsole "-filter : Turn on texture filter"
        printconsole "-nofilter : Turn off texture filter"
        printconsole "-nowide : Turn off widescreen mode"
        printconsole "-opengl : Use OpenGL for graphics (default)"
        printconsole "-software : Use software renderer (NOT FULLY SUPPORTED)"
        printconsole "-vsync : Set vertical sync on"
        printconsole "-novsync : Set vertical sync off"
        printconsole "-bgra : Use BGRA textures"
        printconsole "-nobgra : Disable BGRA textures (use if you're seeing swapped red / blue)"
        printconsole "-low : Low quality mode. Improves speed."
        printconsole "-nospeedlimit : Program will not limit the frame rate"
        printconsole "-sleep : Consume less CPU cycles (can cause slowdowns)"
        printconsole "-quiet : Disable all console messages"
        printconsole "-debug : Enable debug messages"
        printconsole "-createshortcut : Create desktop / menu shortcuts"
        printconsole
        osgl_end
	end
    end if
next i
end if

#ifdef _osgl_noscreen_
	exit sub
#endif

'captura informacoes da screen
'ScreenInfo [ w ] [, [ h ] [, [ depth ] [ , [ bpp ] [ , [ pitch ] [ , [ rate ] [, driver ]]]]]
'screeninfo myscreen.originalx,myscreen.originaly
'screencontrol GET_SCREEN_SIZE,myscreen.originalx,myscreen.originaly
'GET_DESKTOP_SIZE=3
'GET_SCREEN_SIZE=4

screencontrol 4,myscreen.originalx,myscreen.originaly 'GET_SCREEN_SIZE
if myscreen.originalx<1 or myscreen.originaly<1 then
	screencontrol 3,myscreen.originalx,myscreen.originaly 'GET_DESKTOP_SIZE
end if

printconsole "Screen : Detected "+str(myscreen.originalx)+"x"+str(myscreen.originaly)+" desktop."

'screencontrol 8,myscreen.monitorrefresh 'GET_SCREEN_REFRESH
'Screeninfo [ w ] [, [ h ] [, [ depth ] [ , [ bpp ] [ , [ pitch ] [ , [ rate ] [, driver ]]]]]
screeninfo ,,,,,myscreen.monitorrefresh
printconsole "Screen : Monitor refresh is "+str(myscreen.monitorrefresh)+" Hz."

if x=0 then myscreen.x=myscreen.originalx else myscreen.x=x
if y=0 then myscreen.y=myscreen.originaly else myscreen.y=y
if realx=0 then
	myscreen.realx=myscreen.originalx
	realy=0
	#ifdef _osgl_xscreen_
		myscreen.realx=_osgl_xscreen_
	#endif
else
	myscreen.realx=realx
end if
if realy=0 then
	myscreen.realy=myscreen.originaly
	#ifdef _osgl_yscreen_
		myscreen.realy=_osgl_yscreen_
	#endif
else
	myscreen.realy=realy
end if
'Enable widescreen mode (16:10 proportion)
if myscreen.widescreen=0 then myscreen.cutpixels=myscreen.x/12
myscreen.widepixels=myscreen.x/12
if myscreen.windownoframe then fullscreen=0
myscreen.fullscreen=fullscreen
#ifdef _osgl_windowed_
	fullscreen=0 : myscreen.fullscreen=0
#endif
myscreen.depth=depth
myscreen.xyproportion=myscreen.x/(myscreen.y+2*myscreen.cutpixels)
myscreen.xcutpixels=myscreen.xyproportion*myscreen.cutpixels
myscreen.mysyncrate=syncrate
myscreen.maxsyncrate=1.05*myscreen.mysyncrate
myscreen.interframetime=1/syncrate
myscreen.fovy=45
myscreen.tanfovy=1/(2*tan(RADIANS(myscreen.fovy/2)))
'abrobro
'myscreen.eyez=myscreen.y*myscreen.tanfovy
'myscreen.far+=myscreen.eyez
myscreen.eyez=-myscreen.y*myscreen.tanfovy
myscreen.far-=myscreen.eyez
if syncrate=0 then myscreen.interframetime=0:myscreen.cansleep=1

'Prepara a screen OpenGL e muda resolução se necessário
#IFDEF _osgl_softrender_
    myscreen.useopengl=0
#ENDIF

'fullscreen
if fullscreen then
    if osgl_ScreenSupported(myscreen.realx,myscreen.realy,depth)=0 then
        printconsole "Screen : "+str(myscreen.realx)+"x"+str(myscreen.realy)+", "+str(myscreen.depth)+" bit - resolution not supported!"
        myscreen.fullscreen=0
    else
        printconsole "Screen : Using "+str(myscreen.realx)+"x"+str(myscreen.realy)+", "+str(myscreen.depth)+" bit, full screen."
    end if
end if

printconsole "Screen : Sync rate is "+str(myscreen.mysyncrate)+" frames per second."

'window (deixar separado)
if fullscreen=0 then
    'adjust if window bigger than desktop
    if myscreen.realx>=myscreen.originalx or myscreen.realy>=myscreen.originaly then
        printconsole "Screen : Warning! Can't create a window bigger than the desktop. "
        myscreen.realx=myscreen.x:myscreen.realy=myscreen.y
    end if
    printconsole "Screen : Using  "+str(myscreen.realx)+"x"+str(myscreen.realy)+", "+str(myscreen.depth)+" bit, window."
end if

'Enable / disable vsync for linux. Must be done before creating OpenGL context.
myscreen.vsync=vsync

'if myscreen.vsync<>-1 then
'    printdebug "Screen : __GL_SYNC_TO_VBLANK="+trim(str(myscreen.vsync))
'    SetEnviron("__GL_SYNC_TO_VBLANK="+trim(str(myscreen.vsync))) 'nvidia
'    SetEnviron("LIBGL_SYNC_REFRESH="+trim(str(myscreen.vsync))) 'amd / ati
'end if

if myscreen.useopengl=0 then
    myscreen.numpages=2
    printconsole "Screen : WARNING! Using SOFTWARE RENDERER. This is NOT fully supported!!!"
    myscreen.realx=myscreen.x
    myscreen.realy=myscreen.y
    myscreen.texturescale2x=0
    'myscreen.realx=320
    'myscreen.realy=240
end if

myscreen.ratiox=myscreen.realx/myscreen.x
myscreen.ratioy=myscreen.realy/myscreen.y

myscreen.antialias=antialias

printconsole "Screen : Setting screen mode . . . ";

osgl_setvideomode()

'screenres myscreen.realx,myscreen.realy,myscreen.depth,myscreen.numpages,myscreen.switches
'screenres 640,480,32,,1

'screenres 800,600,32,,&h02
If ScreenPtr =0 Then
    printconsole "ERROR! Can't set video mode!"
    osgl_popup "ERROR","Can't set video mode!"
    end 1
else
	screeninfo 2, myscreen.handle 'GET_WINDOW_HANDLE 
    printconsole "OK! HWND="+str(myscreen.handle)
    myscreen.started=1
End If

'clear all buffers
#IFNDEF _osgl_softrender_
	for ii as integer=1 to 3
		glClear  GL_COLOR_BUFFER_BIT OR GL_DEPTH_BUFFER_BIT
		flip
	next ii
#ENDIF

'set font size
if myscreen.currentfontsize<>16 then
    Width myscreen.realx\8, myscreen.realy\16
    myscreen.currentfontsize=16
end if

'set working page for software mode
if myscreen.useopengl=0 then ScreenSet 1, 0

'screenres realx,realy,depth,,fullscreen*&h01 or &h02 or &h04 or &h40 or antialias*&h40000,syncrate

'muda para o diretorio do binário
chdir(exepath)

if wtitle="" then wtitle=ucase(appname)
WindowTitle wtitle
'If myscreen.fullscreen Then setmouse ,,0 'hide mouse
setmouse ,,0 'hide mouse

osgl_getwindowxid

if myscreen.suspendscreensaver then osgl_screensaver 0

'   glrenderer as string
  '  glvendor as string
'    glversion as string
'Dim GlRen As String
'Dim GlVen As String
'Dim GlVer As String
'Dim GlExt As String

'Dim As Integer i, lines

'ScreenRes scr_width,scr_height,scr_bpp,,FB.GFX_OPENGL
'GlRen = *glGetString(GL_RENDERER)
'GlVen = *glGetString(GL_VENDOR)
'GlVer = *glGetString(GL_VERSION)

#IFNDEF _osgl_softrender_
if myscreen.useopengl then
    myscreen.glrenderer=*glGetString(GL_RENDERER)
    printconsole "OpenGL : GPU / Renderer = ";myscreen.glrenderer
    myscreen.glvendor=*glGetString(GL_VENDOR)
    printconsole "OpenGL : Vendor = ";myscreen.glvendor
    myscreen.glversion=*glGetString(GL_VERSION)
    printconsole "OpenGL : Driver version = ";myscreen.glversion
    printconsole "OpenGL : OpenGL Version = "+str(val(myscreen.glversion))
    glGetIntegerv(GL_MAX_TEXTURE_SIZE, @myscreen.maxtexturesize)
    printconsole "OpenGL : MAX texture size = ";myscreen.maxtexturesize

	if myscreen.texturescale2x=-1 then
		if myscreen.maxtexturesize<4096 then
			printconsole "OpenGL : Texture scaler disabled by default."
			myscreen.texturescale2x=0
		else
			printconsole "OpenGL : Texture scaler enabled by default."
			myscreen.texturescale2x=1
		end if
	end if

    printconsole "OpenGL : extensions = ";
    'ScreenControl FB.GET_GL_EXTENSIONS, myscreen.glextensions
    myscreen.glextensions=*glGetString(GL_EXTENSIONS)
    printconsole myscreen.glextensions

	'if (*glGetIntegerV(GL_MAJOR_VERSION))>=3 then '0x821B
	'if (*glGetIntegerV(GL_MINOR_VERSION))>=1 then '0x821C
	if val(myscreen.glversion) >= 3.1 then
		printconsole "OpenGL : Found OpenGL version 3.1 or newer."
		if (InStr(myscreen.glextensions, "GL_ARB_compatibility") = 0) then
			printconsole "OpenGL : WARNING : GL_ARB_compatibility is NOT detected! Starting to pray..."
		else
			printconsole "OpenGL : GL_ARB_compatibility detected! Ok!"
		end if
	end if
	'end if
	'end if
	If (InStr(myscreen.glextensions, "GL_NVX_gpu_memory_info") ) Then
		printconsole "OpenGL : GL_NVX_gpu_memory_info is available."
		dim as integer dedVideoMem=0,totalAvailableMem=0, curAvailableMem=0, evictionCount=0, evictedMem=0
		glGetIntegerv(&h9047, @dedVideoMem)
		glGetIntegerv(&h9048, @totalAvailableMem)
		glGetIntegerv(&h9049, @curAvailableMem)
		glGetIntegerv(&h904A, @evictionCount)
		glGetIntegerv(&h904B, @evictedMem)
		printconsole "OpenGL : dedicated video memory = "+str(dedvideomem)
		printconsole "OpenGL : total available memory = "+str(totalAvailableMem)
		printconsole "OpenGL : current available memory = "+str(curAvailableMem)
		printconsole "OpenGL : eviction count = "+str(evictionCount)
		printconsole "OpenGL : evicted memory = "+str(evictedMem)
	end if

	If (InStr(myscreen.glextensions, "GL_ATI_meminfo") ) Then
		'VBO_FREE_MEMORY_ATI                     0x87FB
		'TEXTURE_FREE_MEMORY_ATI                 0x87FC
		'RENDERBUFFER_FREE_MEMORY_ATI            0x87FD
		'Total memory free in the pool: 86619 Kbyte
		'Largest available free block in the pool: 86615 Kbyte
		'Total auxiliary memory free: 1535668 Kbyte
		'Largest auxiliary free block: 13056 Kbyte

		printconsole "OpenGL : GL_ATI_meminfo is available."
		dim as integer vbofreemem(3), texfreemem(3), renderbufferfreemem(3)
		glGetIntegerv(&h87FB, @vbofreemem(0))
		glGetIntegerv(&h87FC, @texfreemem(0))
		glGetIntegerv(&h87FD, @renderbufferfreemem(0))
		printconsole "OpenGL : VBO free memory : Total memory free in the pool = "+str(vbofreemem(0))
		printconsole "OpenGL : VBO free memory : Largest available free block in the pool = "+str(vbofreemem(1))
		printconsole "OpenGL : VBO free memory : Total auxiliary memory free = "+str(vbofreemem(2))
		printconsole "OpenGL : VBO free memory : Largest auxiliary free block = "+str(vbofreemem(3))

		printconsole "OpenGL : texture free memory : Total memory free in the pool = "+str(texfreemem(0))
		printconsole "OpenGL : texture free memory : Largest available free block in the pool = "+str(texfreemem(1))
		printconsole "OpenGL : texture free memory : Total auxiliary memory free = "+str(texfreemem(2))
		printconsole "OpenGL : texture free memory : Largest auxiliary free block = "+str(texfreemem(3))

		printconsole "OpenGL : renderbuffer memory : Total memory free in the pool = "+str(renderbufferfreemem(0))
		printconsole "OpenGL : renderbuffer memory : Largest available free block in the pool = "+str(renderbufferfreemem(1))
		printconsole "OpenGL : renderbuffer memory : Total auxiliary memory free = "+str(renderbufferfreemem(2))
		printconsole "OpenGL : renderbuffer memory : Largest auxiliary free block = "+str(renderbufferfreemem(3))
	end if

    If (InStr(myscreen.glextensions, "_texture_rectangle") =0 ) Then myscreen.nonsquare=0:printconsole "OpenGL : WARNING : video card is NOT capable of non-square textures." else myscreen.nonsquare=1
    If (InStr(myscreen.glextensions, "_texture_non_power_of_two") =0) Then myscreen.nonpot=0:printconsole "OpenGL : video card is NOT capable of non-power-of-two textures." else myscreen.nonpot=1
    If (InStr(myscreen.glextensions, "_EXT_bgra") <> 0) Then
        printconsole "OpenGL : video card supports BGRA textures : ";
        if myscreen.usebgra then
            myscreen.usebgra=1
            printconsole "using it."
        else
            printconsole "NOT using it."
        end if
    end if

	if myscreen.usetexturecompression=-1 then
		if (instr(lcase(myscreen.glrenderer), "intel")<>0) or (instr(lcase(myscreen.glrenderer), "mesa")<>0) then
			printconsole "OpenGL : texture compression is disabled by default (Mesa/Intel). Use -texturecompression to enable it."
			myscreen.usetexturecompression=0
		else
			myscreen.usetexturecompression=1
		end if
	end if

	if myscreen.usefrontbuffer=-1 then
		if (instr(lcase(myscreen.glrenderer), "intel")<>0) or (instr(lcase(myscreen.glrenderer), "mesa")<>0) then
			printconsole "OpenGL : WARNING: (Mesa/Intel) front buffer reads are enabled. Use -nofrontbuffer if you have problems."
			myscreen.usefrontbuffer=1
		else
			myscreen.usefrontbuffer=1
		end if
	end if

    If (InStr(myscreen.glextensions, "_texture_compression") <> 0) Then
        printconsole "OpenGL : video card supports texture compression : ";
        if myscreen.usetexturecompression=1 then
			myscreen.textureformat=GL_COMPRESSED_RGBA
            printconsole "using it."
        else
			myscreen.usetexturecompression=0
			myscreen.textureformat=GL_RGBA
            printconsole "NOT using it."
        end if
    end if

    If (InStr(myscreen.glextensions, "_ARB_imaging") =0 )  then
        printconsole "OpenGL : GL_ARB_imaging is NOT supported."
	myscreen.useconstantcolor=0
    else
        printconsole "OpenGL : GL_ARB_imaging is supported. Using it."
	myscreen.useconstantcolor=1
    end if

'glBindBufferARB=ScreenGLProc("glBindBufferARB")
'if glBindBufferARB=0 then glBindBufferARB=ScreenGLProc("glBindBuffer")

'if glBindBufferARB=0 then
'	printconsole "OpenGL : Warning : GL_ARB_vertex_buffer_object is NOT supported!"
'else
'	printconsole "OpenGL : GL_ARB_vertex_buffer_object is supported."
'end if

    osgl_setvsync(myscreen.vsync)

	if myscreen.vsync then
		if abs(myscreen.monitorrefresh-myscreen.mysyncrate)>.1*myscreen.mysyncrate then
			myscreen.trustvsync=0
			printconsole "Screen : Speed control : Monitor refresh won't match frame rate."
		else
			myscreen.trustvsync=1
			printconsole "Screen : Speed control : Will use vsync to control speed."
		end if
	else
		myscreen.trustvsync=0
		printconsole "Screen : Speed control : Vsync is off."
	end if

    osgl_set3dscreen()
    glPushAttrib GL_ALL_ATTRIB_BITS

end if
#endif

if myscreen.screencopytexture=0 then osgl_createtexture(myscreen.screencopytexture,myscreen.realx,myscreen.realy)

myscreen.fps=myscreen.mysyncrate
myscreen.fpscounter=myscreen.mysyncrate
myscreen.fpstimer=0
myscreen.interframetimer=timer()


'audio
if useaudio=0 then osgl_disableaudio()

#IFNDEF _SDL_LINK_
    osgl_SDLdyload
#ENDIF

osgl_initaudio()

osgl_initinput()

for ii2 as integer= 1 to 3
	osgl_cls()
	osgl_sync(1)
next ii2


end sub   'sub osgl_init(byval wtitle as string="", byval x as const integer=0, byval y as const integer=0,  byval syncrate as integer =60, byval setnumberofplayers as integer=4,byval  realx as integer=0, byval  realy as integer=0, byval depth as integer =32, byval fullscreen as integer =1, byval antialias as integer =0,byval vsync as integer =1,byval useaudio as const integer=1)



#define osgl_useopengl myscreen.useopengl

'tmp var
'dim shared i as integer =0
'dim shared j as integer =0
'dim shared k as integer =0
'dim shared l as integer =0

'dim shared fps as integer =0
'dim shared fpstimer as single =0
'dim shared fpscounter as integer =0
'dim shared mysyncrate as integer =0
'dim shared interframetimer as single =0
'dim shared interframetime as single =0
'dim shared interframetime2 as single =0
'dim shared interframeadjust as single =0
'dim shared mysyncratebak as integer


'FLC
TYPE flcHeaderType field=1
    Size AS uinteger               'Size (in mybytes) of entire Flic file
    ID AS ushort              'Always &hAF11 for FLI files
    flcFrames AS ushort          'Number of flcFrames (not including ring flcFrame)
    Xres AS ushort            'Always 320 for FLI files
    Yres AS ushort            'Always 200 for FLI files
    ColorBits AS ushort       'Always 8 for FLI files (bits per pixel)
    Flags AS ushort           'Always 0 for FLI files
    Speed AS uinteger           'Pauses 1/70 second between flcFrames (FLI only)
    reserved1 as ushort
    created as uinteger
    creator as uinteger
    updated as uinteger
    updater as uinteger
    aspect_dx as ushort
    aspect_dy as ushort
    reserved(1 to 86) as ubyte
    'Reserved AS STRING * 109     '110 bytes : last one is null
    'Reserved AS STRING * 110     '110 bytes : last one is null
END TYPE

'TYPE flcHeaderType field=1
'    Size AS uinteger               'Size (in mybytes) of entire Flic file
'    ID AS ushort              'Always &hAF11 for FLI files
'    flcFrames AS ushort          'Number of flcFrames (not including ring flcFrame)
'    Xres AS ushort            'Always 320 for FLI files
'    Yres AS ushort            'Always 200 for FLI files
'    ColorBits AS ushort       'Always 8 for FLI files (bits per pixel)
'    Flags AS ushort           'Always 0 for FLI files
'    Speed AS ushort           'Pauses 1/70 second between flcFrames (FLI only)
'    reserved(1 to 110) as ubyte
    'Reserved AS STRING * 109     '110 bytes : last one is null
    'Reserved AS STRING * 110     '110 bytes : last one is null
'END TYPE

TYPE flcFrameflcChunkType field=1
    Size AS uinteger               'Size of flcFrame flcChunk, including flcHeader
    ID AS ushort              'Always &hF1FA for FLI files
    flcChunks AS ushort          'Number of subordinate flcChunks in flcFrame flcChunk
    reserved(1 to 8) as ubyte
    'Reserved AS STRING * 7        '8 bytes : last one is null
    'Reserved AS STRING * 8        '8 bytes : last one is null
END TYPE

TYPE flcDataChunkType field=1
    Size AS uinteger               'Size of data flcChunk, including flcHeader
    ID AS ushort              'Data Type ID (see below)
    'ID AS ubyte              'Data Type ID (see below)
END TYPE

DIM shared flcHeader AS flcHeaderType
DIM shared flcFrameflcChunk AS flcFrameflcChunkType
DIM shared flcDataChunk AS flcDataChunkType
'print "chunk=";sizeof(flcDataChunk)

dim shared flcPalette(255) as uinteger
dim shared flcFileNum as integer=0
dim shared flcFrame as ushort

dim shared flcscreendepth as Uinteger=32
dim shared flcoglx as Uinteger
dim shared flcogly as Uinteger
dim shared flcdriver as string
dim shared flcuseopengl as integer=0

dim shared flcusetransparency as integer=1
'dim shared flctransparentcolor as uinteger=rgba(0,0,0,0)

'dim shared flcbuffer as FBImage ptr
dim shared flcbuffer as ubyte ptr
dim shared flcbufferpixels as uinteger ptr
dim shared flcTexture As uinteger
dim shared flcpitch as integer

'dim shared xrot as single
'dim shared yrot as single
'dim shared zrot as single

union colortype
	colour as uinteger
	type
		b as ubyte
		g as ubyte
		r as ubyte
		a as ubyte
	end type
end union

'dim ttas as colortype
'ttas.r=45
'printconsole ttas.r
'printconsole ttas.g
'printconsole ttas.b
'printconsole ttas.a
'ttas.colour=rgba(255,255,255,255)
'printconsole ttas.r
'printconsole ttas.g
'printconsole ttas.b
'printconsole ttas.a
'end

'macros de cores
#define RGBAR(x) (CUInt(x) Shr 16 And 255)
#define RGBAG(x) (CUInt(x) Shr  8 And 255)
#define RGBAB(x) (CUInt(x) And 255)
#define RGBAA(x) (CUInt(x) Shr 24 and 255)

#define RGBA2BGRA(x) RGBA(RGBAB(x),RGBAG(x),RGBAR(x),RGBAA(x))

#macro osgl_setalpha(cor, a)
	'cor1=osgl_setalpha(cor0,a)
	rgba(rgbar(cor),rgbag(cor),rgbab(cor),a)
#endmacro

#ifdef fiduosofidsf
function min(a as single,b as single) as single
	function=int(iif((a)<(b),(a),(b)))
end function

function HLSA(byval h as integer, byval l as integer, byval s as integer, byval a as integer) as uinteger

h=int(h*240.0/255.0)
l=int(l*240.0/255.0)
s=int(s*240.0/255.0)

  dim as integer OffsetLightness, OffsetSaturation
  dim as colortype color2

	if (H < 0) then
		H = (240 - H) mod 24
	else
		H = H  mod 240
	end if

    if (H <  80) then
		Color2.R = Min(255, 255 * (80 - H)  / 40)
	else
		if (H > 160) then Color2.R = Min(255, 255 * (H - 160) / 40)
	end if

  if (H < 160) then Color2.G = Min(255, 255 * (80 - Abs(H -  80)) / 40)
  if (H >  80) then Color2.B = Min(255, 255 * (80 - Abs(H - 160)) / 40)

  if (S < 240) then
    Color2.colour = Color2.colour * (S / 240.0)
    OffsetSaturation = 128 * (240 - S) / 240
    Color2.R += OffsetSaturation
    Color2.G += OffsetSaturation
    Color2.B += OffsetSaturation
  end if

  L = Min(240, L)
  Color2.colour = Color2.colour * ((120 - Abs(L - 120)) / 120)

  if (L > 120) then
    OffsetLightness = 256 * (L - 120) / 120
    Color2.R += OffsetLightness
    Color2.G += OffsetLightness
    Color2.B += OffsetLightness
  end if

  color2.a=a

  function=Color2.colour
end function
#endif


#if __FB_LANG__="fb"
Function RGB16(Byval r As Ubyte, Byval g As Ubyte, Byval b As Ubyte) As Ushort
    r Shr= 3:g Shr= 2:b Shr= 3
    Return (r Shl 11) Or (g Shl 5) Or b
End Function
#endif

Function RGBAf(Byval r as single, Byval g as single, Byval b as single, byval a as single) As Uinteger
    Return rgba(r*255,g*255,b*255,a*255)
End Function

function osgl_playercolor(byval i as integer=1, teamplay as integer=0) as uinteger
	if teamplay=0 then
		select case i
			case 1:function=rgba(0,255,0,255)
			case 2:function=rgba(255,255,0,255)
			case 3:function=rgba(32,96,255,255)
			case 4:function=rgba(255,0,0,255)
			case 5:function=rgba(255,0,255,255)
			case 6:function=rgba(0,255,255,255)
			case 7:function=rgba(255,142,153,255)
			case 8:function=rgba(210,105,30,255)
			case else:function=rgba(64,64,64,255)
		end select
	else
		select case i
			case 1:function=rgba(0,255,0,255)
			case 2:function=rgba(0,200,96,255)
			case 3:function=rgba(255,0,0,255)
			case 4:function=rgba(255,0,64,255)
			case else:function=rgba(128,128,128,255)
		end select
	end if
end function
'circle collision
'distance between two points (2 points)
'DistanceBetween = Sqr((Abs(X2 - X1) ^ 2) + (Abs(Y2 - Y1) ^ 2))
#define DISTANCE(X1,Y1,X2,Y2) Sqr((Abs(CUInt(X2) - CUInt(X1)) ^ 2) + (Abs(CUInt(Y2) - CUInt(Y1)) ^ 2))
#define DISTANCE3D(X1,Y1,Z1,X2,Y2,Z2) Sqr((Abs(CUInt(X2) - CUInt(X1)) ^ 2) + (Abs(CUInt(Y2) - CUInt(Y1)) ^ 2) + (Abs(CUInt(Z2) - CUInt(Z1)) ^ 2))


function osgl_closewindow as integer
#ifdef __FB_LANG__
#if __FB_LANG__="fb"
	Dim e As fb.EVENT
	If (ScreenEvent(@e)) Then function=(e.type=fb.EVENT_WINDOW_CLOSE) : exit function
#endif
#else
	'' Older version - before lang fb
#endif
function=0
end function

'inc , dec
'#define inc(x) x+=1
'#define dec(x) x-=1

'power of two (POT)
#define isPOT(x) ((x) And ((x)-1)) = 0
function makePOT(byval x as uinteger) as uinteger
if isPOT(x) then return x
dim i as uinteger=0
dim res as uinteger=0
do
    i+=1
    res=2^i
loop until res>x
return res
end function

'car return / line feed / end of line / ENTER
const CRLF As string = chr(13,10)
const CR As string = chr(13)
const LF As string = chr(10)
const ASPAS as string = chr(34)

'dir$
const fbArchive=&h20
const fbDirectory=&h21

'limits
#ifndef maxtexture
    #define maxtexture 65025
#endif

#ifndef maxparticle
    #define maxparticle 65025
#endif

#ifndef maxsprite
    '#define maxsprite 255
    #define maxsprite 65025
#endif

'particles
type osgl_particletype
	text as string = ""
    exist as integer = 0
    x as single = 0
    y as single = 0
    z as single = 0
    mirror as integer=0
    flipp as integer=0
    texture as integer = 0
    xscale as single = 1
    yscale as single = 1
    dxscale as single = 0
    dyscale as single = 0
    firstframe as integer = 0
    lastframe as integer = 0
    duration as integer = 0
    interframe as integer = 0
    elapsed as integer = 0
    dx as single = 0
    dy as single = 0
    dz as single = 0
    ax as single = 0
    ay as single = 0
    az as single = 0
    ybounce as integer = 65025
    blendmode as integer = 1
	Union
		colour As uinteger
		type
			b as ubyte
			g as ubyte
			r as ubyte
			a as ubyte
		end type
	End Union
    valpha as single = 255
    dalpha as single = 0
    angle as single = 0
    dangle as single = 0
end type

dim shared particle(maxparticle) as osgl_particletype
dim shared lastparticle as integer =-1
dim shared myparticle as integer =0

'blendmodes
const osgl_blendmode_noblend=0
const osgl_blendmode_normal=1
const osgl_blendmode_negative=-1
const osgl_blendmode_dark=2
const osgl_blendmode_glow=3
const osgl_blendmode_glow2=4
const osgl_blendmode_glow3=13
const osgl_blendmode_outline=14
const osgl_blendmode_noalpha=7
const osgl_blendmode_cutedges=9
const osgl_blendmode_nooutline=12

'orientation
const osgl_orientation_normal=0
const osgl_orientation_billboard=-1
const osgl_orientation_conebillboard=1


declare sub osgl_Render(    byval x1 as single=0,byval y1 as single=0,byval xcenter as single=0,byval ycenter as single=0,_
                byval z as single=0,_
                byval texturenumber as integer=0,byval frame as integer=0,_
                byval angle as single=0,_
                byval xscale as single=1,byval yscale as single=1,_
                byval xoffset as single=0,byval yoffset as single=0,_
                byval xstretch as single=1,byval ystretch as single=1,_
                byval mirror as integer=0,byval flipp as integer=0,_
                byval xrep as single=1,byval yrep as single=1,byval xscroll as single=0,byval yscroll as single=0,_
                byval blendmode as integer=1,byval depthtest as integer=0,_
                byval colour as uinteger=rgba(255,255,255,255),byval orientation as integer=0)
                'byval r as ubyte,byval g as ubyte,byval b as ubyte,byval a as ubyte)

'sprites
type osgl_spritetype
    exist as integer = 0
    x as single = 0
    y as single = 0
    z as single = 0
    prio as integer = 0
    texture as integer = 0
    frame as integer = 0
    angle as single = 0
    xscale as single = 1
    yscale as single = 1
    xstretch as single = 1
    ystretch as single = 1
    xrep as single = 1
    yrep as single = 1
    xcenter as single = 0
    ycenter as single = 0
    xoffset as single = 0
    yoffset as single = 0
    xscroll as single = 0
    yscroll as single = 0
    mirror as integer = 0
    flipp as integer = 0
    blendmode as integer = 1
    depthtest as integer = 0
    orientation as integer=0
	Union
		colour As uinteger
		type
			b as ubyte
			g as ubyte
			r as ubyte
			a as ubyte
		end type
	End Union
end type

dim shared sprite() as osgl_spritetype
dim shared lastsprite as uinteger=1
dim shared lastdrawnsprite as integer=0
dim shared osgl_putparam(1) as osgl_spritetype

#define  osgl_putangle(x) osgl_putparam(0).angle=(x)
#define  osgl_putcolor(x) osgl_putparam(0).colour=(x)
#define  osgl_putprio(x) osgl_putparam(0).prio=(x)
#define  osgl_putmirror(x) osgl_putparam(0).mirror=(x)
#define  osgl_putflipp(x) osgl_putparam(0).flipp=(x)
#define  osgl_putblendmode(x) osgl_putparam(0).blendmode=(x)
#define  osgl_putorientation(x) osgl_putparam(0).orientation=(x)
#define  osgl_putdepthtest(x) osgl_putparam(0).depthtest=(x)
#define  osgl_putstretch(x,y) osgl_putparam(0).xstretch=(x):osgl_putparam(0).ystretch=(y)
#define  osgl_putscale(x,y) osgl_putparam(0).xscale=(x):osgl_putparam(0).yscale=(y)
#define  osgl_putcenter(x,y) osgl_putparam(0).xcenter=(x):osgl_putparam(0).ycenter=(y)
#define  osgl_putoffset(x,y) osgl_putparam(0).xoffset=(x):osgl_putparam(0).yoffset=(y)
#define  osgl_putscroll(x,y) osgl_putparam(0).xscroll=(x):osgl_putparam(0).yscroll=(y)
#define  osgl_putrep(x,y) osgl_putparam(0).xrep=(x):osgl_putparam(0).yrep=(y)

#define  osgl_putclear osgl_putparam(0)=osgl_putparam(1)


'texturas
type texturetype
  number as integer = -1
  xsize as uinteger = 0	'sempre power of two (POT)
  ysize as uinteger  = 0	'sempre power of two (POT)
  xslices as uinteger = 1
  yslices as uinteger = 1
  xslicesize as uinteger = 0
  yslicesize as uinteger = 0
  xslicesizefloat as double = 0
  yslicesizefloat as double = 0
  lastframe as integer = 0
  flipped as uinteger = 0
  ispng as integer = 0
  imagedata as FBImage ptr
  tmpimage as FBImage ptr
  'imagedata as ubyte ptr
  'tmpimage as ubyte ptr
  currentframe as integer=-1
  currenttext as string=chr(10)
  filename as string
  scaled as integer=1
end type

dim shared lasttexture as uinteger=1
dim shared texturearray() as texturetype
dim shared currenttexture as integer
redim texturearray(1 to maxtexture) as texturetype
redim soundsfx(lastsfx) as Mix_Chunk ptr
redim sprite(1 to lastsprite) as osgl_spritetype
'dim shared texttexture as texturetype

sub osgl_bindtexture(byval number as integer)
#IFNDEF _osgl_softrender_
dim as integer curtex
glGetIntegerv(GL_TEXTURE_BINDING_2D, @curtex)
if number<>curtex then
	glEnable GL_TEXTURE_2D
	glBindTexture GL_TEXTURE_2D, number
	myscreen.currenttexture=number
end if
#ENDIF
end sub

sub osgl_textureinfo(byval number as uinteger,byref x as uinteger=0,byref y as uinteger=0,byref lastframe as integer=0)
x=texturearray(number).xslicesize
y=texturearray(number).yslicesize
lastframe=texturearray(number).lastframe
end sub

#define osgl_texturelastframe(number) texturearray(number).lastframe
#define osgl_texturexsize(number) texturearray(number).xslicesize
#define osgl_textureysize(number) texturearray(number).yslicesize

type textureprecalctype
tx(3) as double
ty(3) as double
sx(3) as double
sy(3) as double
sz(3) as double
xslicesize as double
yslicesize as double
xslice as integer
yslice as integer
end type
dim shared textureprecalc as textureprecalctype

'declare sub osgl_loadtexture(byref texturenumber as integer, byval imagefile as string)
'declare sub osgl_loadtextureTGA(byref texturenumber as integer, byval filename as string)
'declare sub osgl_loadtexturePNG(byref texturenumber as integer, byval filename as string)
'declare sub osgl_loadtexturePNG2(byref texturenumber as integer, byval filename as string, byval keycolor as uinteger=0)
declare sub osgl_SetBlendMode(byval blendmode as integer)
declare sub osgl_texturetext(byref texturenumber as integer, byval textlength as uinteger, byval textlines as uinteger, byval text as string, byval textcolor as uinteger,byval font as any ptr,byval fontsize as uinteger)
declare sub osgl_ChangeColor(byval buffer as any ptr, byval oldcolor as uinteger, byval newcolor as uinteger)

dim shared glfontbase as uinteger                      ' Base Display List For The Font
dim shared glnehefontbase as uinteger                      ' Base Display List For The Font
dim shared glhalfnehefontbase as uinteger                      ' Base Display List For The Font



'declare sub osgl_loadsound(byref number as integer,byval filename as string)
'declare sub osgl_PlaySound(byval number as integer,byval leftvolume as integer, byval rightvolume as integer,byval channel as integer,byval loops as integer)
'declare sub osgl_loadmusic(byval filename as string)
'declare sub osgl_playmusic()

'declare sub osgl_particle(    byval x as single,byval y as single,byval z as single,_
'                        byval texturenumber as integer,_
'                        byval xscale as single,byval yscale as single,byval dxscale as single,byval dyscale as single,_
'                        byval firstframe as integer,byval lastframe as integer, byval duration as integer,_
'                        byval dx as single,byval dy as single,byval ax as single,byval ay as single,byval ybounce as integer,_
'                        byval angle as single,byval dangle as single,_
'                        byval blendmode as integer,_
'                        byval r as ubyte,byval g as ubyte,byval b as ubyte,byval a as ubyte,byval dalpha as single, text)

'declare sub osgl_moveparticles(byval x as single,byval y as single)
'declare sub osgl_clearparticles()

'DECLARE sub FLCopen (FileName as string)
'DECLARE function FLCrendernextframe() as FBImage ptr
'DECLARE SUB FLCplay (flcx as integer,flcy as integer,flcscalex as single,flcscaley as single,FileName as string,loops as integer,delay as single, byval usetransparency as integer)

DECLARE sub glUploadTexture(byref texture as integer, byval buffer as any ptr, byval mipmap as integer=0, byval useBGRA as integer=0, byval filter as integer=1)


'sub osgl_savebuffer(byref buffer as any ptr,byref filename as string)

'end sub

sub osgl_SetTextureFrameSize (byval texturenumber as integer=0,byval xsize as uinteger=-1,byval ysize as uinteger=-1,byval lastframe as integer=-999)
    texturearray(texturenumber).xslicesize=xsize
    texturearray(texturenumber).yslicesize=ysize
    texturearray(texturenumber).xslices=texturearray(texturenumber).xsize\xsize
    texturearray(texturenumber).yslices=texturearray(texturenumber).ysize\ysize
    texturearray(texturenumber).xslicesizefloat=texturearray(texturenumber).xslicesize/texturearray(texturenumber).xsize
    texturearray(texturenumber).yslicesizefloat=texturearray(texturenumber).yslicesize/texturearray(texturenumber).ysize
    texturearray(texturenumber).lastframe=texturearray(texturenumber).xslices*texturearray(texturenumber).yslices
    if lastframe<>-999 then texturearray(texturenumber).lastframe=lastframe
end sub

sub osgl_SetTextureFrames (byval texturenumber as integer=0,byval xslices as uinteger=1,byval yslices as uinteger=1,byval lastframe as integer=1)
    if xslices=0 then xslices=1
    if yslices=0 then yslices=1
    texturearray(texturenumber).xslices=xslices
    texturearray(texturenumber).yslices=yslices
    texturearray(texturenumber).xslicesize=texturearray(texturenumber).xsize/xslices
    texturearray(texturenumber).yslicesize=texturearray(texturenumber).ysize/yslices
    texturearray(texturenumber).xslicesizefloat=texturearray(texturenumber).xslicesize/texturearray(texturenumber).xsize
    texturearray(texturenumber).yslicesizefloat=texturearray(texturenumber).yslicesize/texturearray(texturenumber).ysize
    texturearray(texturenumber).lastframe=lastframe
end sub

'3d lights
Dim Shared LightDiffuse(0 To 3) As Single => {3, 3, 3, 1}
Dim Shared LightPosition(0 To 3) As Single => {0, 0, 0, 1}
Dim Shared LightDirection(0 To 2) As Single => {0, -1, -1}
dim Shared osgl_lookat_matrix(16) as GLfloat
dim Shared osgl_lookat_matrix1(16) as GLfloat
dim Shared osgl_lookat_matrix2(16) as GLfloat

#IFNDEF _osgl_softrender_
sub osgl_LookAt(byval eyex as GLfloat, byval eyey as GLfloat, byval eyez as GLfloat,_
           byval centerx as GLfloat, byval centery as GLfloat, byval centerz as GLfloat,_
            byval upx as GLfloat, byval upy as GLfloat , byval upz as GLfloat )

'eyey=-eyey
'eyez=-eyez
'centery=-centery
'centerz=-centerz

'printdebug "lokat!"

    dim as GLfloat m(16)
    dim as GLfloat x(3), y(3), z(3)
    dim as GLfloat mag

    '/* Make rotation matrix */
    '/* Z vector */

    z(0) = eyex - centerx
    z(1) = eyey - centery
    z(2) = eyez - centerz
    mag = sqrt(z(0) * z(0) + z(1) * z(1) + z(2) * z(2))

    if (mag) then                   '/* mpichler, 19950515 */
       z(0) /= mag
       z(1) /= mag
       z(2) /= mag
    end if

    '/* Y vector */

    y(0) = upx
    y(1) = upy
    y(2) = upz

    '/* X vector = Y cross Z */

    x(0) = y(1) * z(2) - y(2) * z(1)
    x(1) = -y(0) * z(2) + y(2) * z(0)
    x(2) = y(0) * z(1) - y(1) * z(0)

    '/* Recompute Y = Z cross X */

    y(0) = z(1) * x(2) - z(2) * x(1)
    y(1) = -z(0) * x(2) + z(2) * x(0)
    y(2) = z(0) * x(1) - z(1) * x(0)

    '/* mpichler, 19950515 */
    '/* cross product gives area of parallelogram, which is < 1.0 for
     '* non-perpendicular unit-length vectors; so normalize x, y here
     '*/

    mag = sqrt(x(0) * x(0) + x(1) * x(1) + x(2) * x(2))

    if (mag) then
       x(0) /= mag
       x(1) /= mag
       x(2) /= mag
    end if

    mag = sqrt(y(0) * y(0) + y(1) * y(1) + y(2) * y(2))

    if (mag) then
       y(0) /= mag
       y(1) /= mag
       y(2) /= mag
    end if

 #define MM(row,col)  m(col*4+row)

    MM(0, 0) = x(0)
    MM(0, 1) = x(1)
    MM(0, 2) = x(2)
    MM(0, 3) = 0.0
    MM(1, 0) = y(0)
    MM(1, 1) = y(1)
    MM(1, 2) = y(2)
    MM(1, 3) = 0.0
    MM(2, 0) = z(0)
    MM(2, 1) = z(1)
    MM(2, 2) = z(2)
    MM(2, 3) = 0.0
    MM(3, 0) = 0.0
    MM(3, 1) = 0.0
    MM(3, 2) = 0.0
    MM(3, 3) = 1.0

 #undef MM
	for i as integer=0 to 16
		osgl_lookat_matrix(i)=m(i)
	next i

    glMultMatrixf(@m(0))

    '/* Translate Eye to Origin */

    glTranslatef(-eyex, -eyey, -eyez)

end sub
#ENDIF

sub osgl_Perspective(byval fovy as double, byval aspect as double, byval zNear as double, byval zFar as double)
#IFNDEF _osgl_softrender_
dim as double xmin, xmax, ymin, ymax
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
ymax = zNear * tan(fovy * PI / 360.0)
ymin = -ymax
xmin = ymin * aspect
xmax = ymax * aspect
glFrustum(xmin, xmax, ymin, ymax, zNear, zFar)
glMatrixMode(GL_MODELVIEW)
'glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
'glDepthMask(GL_TRUE)
#ENDIF
end sub

sub osgl_set3dcoords (byval eye as integer=0) '0=normal/left eye  1=right eye
'printdebug "set3dcoords!"
myscreen.secondeye=eye
#IFNDEF _osgl_softrender_
	'myscreen.eyez=0
'    osgl_Perspective myscreen.fovy, myscreen.xyproportion, myscreen.near, myscreen.far   '' Calculate The Aspect Ratio Of The Window
    glMatrixMode GL_MODELVIEW                  '' Select The Modelview Matrix
    glLoadIdentity                             '' Reset The Projection Matrix
    	'if eye then
	'	gluLookAt(0+eyedistance, 0, 10,      eyedistance, 0, 0,          0, 1, 0)
	'else
	'	gluLookAt(0, 0, 10,      0, 0, 0,          0, 1, 0)
	'end if
	'myscreen.eyez=(myscreen.y-(2*myscreen.zoomy))*myscreen.tanfovy
	'printconsole myscreen.cameraxa
	'printconsole myscreen.cameraya
	'printconsole myscreen.cameraza
	glrotatef(myscreen.cameraxa,1,0,0)
	glrotatef(myscreen.cameraya,0,-1,0)
	glrotatef(myscreen.cameraza,0,0,1)
	gltranslatef(-myscreen.camerax,myscreen.cameray,myscreen.cameraz)

	if myscreen.stereo3d and myscreen.drawingtotexture=0 then
		if eye then
			'gluLookAt(myscreen.zoomxcenter+eyedistance, -myscreen.zoomycenter, (myscreen.y-(2*(myscreen.zoomy+eyedistance)))*myscreen.tanfovy,      0, 0, 0,          0, 1, 0)
			'gluLookAt(myscreen.zoomxcenter+myscreen.eyedistance, -myscreen.zoomycenter, (myscreen.y-(2*(myscreen.zoomy+myscreen.eyedistance)))*myscreen.tanfovy,      myscreen.eyedistance, 0, 0,          0, 1, 0)
'			osgl_LookAt(myscreen.eyedistance, 0, myscreen.eyez,      myscreen.eyedistance, 0,0,          0, 1, 0)
		   glMultMatrixf(@osgl_lookat_matrix2(0))
		    	'glTranslatef(-myscreen.eyedistance, 0, -myscreen.eyez)
		    	glTranslatef(-myscreen.eyedistance, 0, 0)
				'glViewport 0, 0, myscreen.realx+myscreen.eyedistance, myscreen.realy
		else
			'gluLookAt(myscreen.zoomxcenter-eyedistance, -myscreen.zoomycenter, (myscreen.y-(2*(myscreen.zoomy+eyedistance)))*myscreen.tanfovy,      0, 0, 0,          0, 1, 0)
			'gluLookAt(myscreen.zoomxcenter-myscreen.eyedistance, -myscreen.zoomycenter, (myscreen.y-(2*(myscreen.zoomy+myscreen.eyedistance)))*myscreen.tanfovy,      -myscreen.eyedistance, 0, 0,          0, 1, 0)
'			osgl_LookAt(-myscreen.eyedistance, 0, myscreen.eyez,      -myscreen.eyedistance, 0, 0,          0, 1, 0)
		    glMultMatrixf(@osgl_lookat_matrix1(0))
		    	'glTranslatef(myscreen.eyedistance, 0, -myscreen.eyez)
		    	glTranslatef(myscreen.eyedistance, 0, 0)
				'glViewport -myscreen.eyedistance, 0, myscreen.realx, myscreen.realy

		end if
	else
		'gluLookAt(myscreen.zoomxcenter, -myscreen.zoomycenter, (myscreen.y-(2*myscreen.zoomy))*myscreen.tanfovy,      0, 0, 0,          0, 1, 0)
		'if billboard=0 then
		'	osgl_LookAt(myscreen.zoomxcenter+myscreen.camerax, -myscreen.zoomycenter-myscreen.cameray, myscreen.eyez+myscreen.cameraz,      myscreen.cameraxl,  -myscreen.camerayl,  myscreen.camerazl,          0, 1, 0)
		'else
			'osgl_LookAt(0, 0, myscreen.eyez,      0,  0,  0,          0, 1, 0)
		'end if
		    'glMultMatrixf(@osgl_lookat_matrix(0))
'			glTranslatef(0, 0, -myscreen.eyez)

		'/* Translate Eye to Origin */


	end if
	'glScalef( 1, -1, -1 ) 'inverte o eixo y 3d=2d

	'glrotatef(myscreen.xangle,1,0,0)
	'glrotatef(myscreen.yangle,0,1,0)
	'glrotatef(myscreen.zangle,0,0,1)


#ENDIF
end sub

sub osgl_camera (byval x as single=0, byval y as single=0, byval z as single=0, byval xl as single=0, byval yl as single=0, byval zl as single=0, byval zangle as single=0)
	'osgl_LookAt(myscreen.zoomxcenter, -myscreen.zoomycenter, (myscreen.y-(2*myscreen.zoomy))*myscreen.tanfovy,      0, 0, 0,          0, 1, 0)
'	x=x
	y=-y
	'z=-z
'	xl=xl
	yl=-yl
	'zl=-zl
	myscreen.camerax=x
	myscreen.cameray=y
	myscreen.cameraz=z
	myscreen.cameraxl=xl
	myscreen.camerayl=yl
	myscreen.camerazl=zl
	myscreen.cameraxa=degrees(atn((yl-y)/(myscreen.eyez)))
	myscreen.cameraya=degrees(atn((xl-x)/(myscreen.eyez)))
	myscreen.cameraza=zangle
	osgl_wrap(myscreen.cameraxa,0.0,359.0)
	osgl_wrap(myscreen.cameraya,0.0,359.0)
	osgl_wrap(myscreen.cameraza,0.0,359.0)
	osgl_set3dcoords
end sub

sub osgl_cameraangle (byval x as single=0, byval y as single=0, byval z as single=0, byval xangle as single=0, byval yangle as single=0, byval zangle as single=0)
'	x=x
	y=-y
	'z=-z
' 	xangle=-xangle
'	yangle=yangle
'	zangle=-zangle
	myscreen.camerax=x
	myscreen.cameray=y
	myscreen.cameraz=z
	myscreen.cameraxl=y+myscreen.eyez*tan(radians(yangle))
	myscreen.camerayl=x+myscreen.eyez*tan(radians(xangle))
	myscreen.cameraxa=xangle
	myscreen.cameraya=yangle
	myscreen.cameraza=zangle
	osgl_wrap(myscreen.cameraxa,0.0,359.0)
	osgl_wrap(myscreen.cameraya,0.0,359.0)
	osgl_wrap(myscreen.cameraza,0.0,359.0)
	osgl_set3dcoords
end sub

sub osgl_suspendcamera
	myscreen.camerax2=myscreen.camerax
	myscreen.cameray2=myscreen.cameray
	myscreen.cameraz2=myscreen.cameraz
	myscreen.cameraxl2=myscreen.cameraxl
	myscreen.camerayl2=myscreen.camerayl
	myscreen.camerazl2=myscreen.camerazl
	osgl_camera()
	osgl_set3dcoords
end sub

sub osgl_restorecamera
	osgl_camera(myscreen.camerax2,myscreen.cameray2,myscreen.cameraz2,myscreen.cameraxl2,myscreen.camerayl2,myscreen.camerazl2)
	osgl_set3dcoords
end sub

'gluproject replacement get screen coords
sub osgl_3dtoscreen (byval objx as single, byval objy as single, byval objz as single, byref x as integer, byref y as integer)

objy=-objy
objz=-objz+myscreen.eyez

	dim as glfloat modelview(15)
	dim as glfloat projection(15)
	glGetFloatv(GL_MODELVIEW_MATRIX , @modelview(0))
	glGetFloatv(GL_PROJECTION_MATRIX , @projection(0))

	dim as glfloat ftempo(7)

      fTempo(0)=modelview(0)*objx+modelview(4)*objy+modelview(8)*objz+modelview(12)  '//w is always 1
      fTempo(1)=modelview(1)*objx+modelview(5)*objy+modelview(9)*objz+modelview(13)
      fTempo(2)=modelview(2)*objx+modelview(6)*objy+modelview(10)*objz+modelview(14)
      fTempo(3)=modelview(3)*objx+modelview(7)*objy+modelview(11)*objz+modelview(15)

      fTempo(4)=projection(0)*fTempo(0)+projection(4)*fTempo(1)+projection(8)*fTempo(2)+projection(12)*fTempo(3)
      fTempo(5)=projection(1)*fTempo(0)+projection(5)*fTempo(1)+projection(9)*fTempo(2)+projection(13)*fTempo(3)
      fTempo(6)=projection(2)*fTempo(0)+projection(6)*fTempo(1)+projection(10)*fTempo(2)+projection(14)*fTempo(3)
      fTempo(7)=-fTempo(2)

	      if(fTempo(7)=0.0) then x=0 : y=0 : exit sub	'//The w value
      fTempo(7)=1.0/fTempo(7)
      fTempo(4)*=fTempo(7)
      fTempo(5)*=fTempo(7)
      fTempo(6)*=fTempo(7)


x=(fTempo(4)*0.5+0.5)*myscreen.x-(myscreen.x/2)
y=-(fTempo(5)*0.5+0.5)*myscreen.y+(myscreen.y/2)

end sub


sub osgl_set3dscreen()

'myscreen.rendermode=1

#IFNDEF _osgl_softrender_

if myscreen.drawingtotexture=0 then
	'glViewport 0, 0, myscreen.realx, myscreen.realy
	glviewport 0, myscreen.blackborders*myscreen.realx*0.0625,myscreen.realx,myscreen.realy - myscreen.blackborders*myscreen.realx*0.125
else
	glViewport 0, 0, myscreen.x, myscreen.y
end if

    glMatrixMode GL_PROJECTION                 '' Select The Projection Matrix
    glLoadIdentity                             '' Reset The Projection Matrix
'glFrustum myscreen.zoomx - myscreen.x/2-myscreen.cutpixels, myscreen.x/2-myscreen.zoomx + myscreen.cutpixels, myscreen.y/2-myscreen.zoomy , myscreen.zoomy-myscreen.y/2,.001,100                                '' Set Up An Ortho Screen
'glFrustum 0, 1, 1, 0,.001,100                                '' Set Up An Ortho Screen

    'gluPerspective myscreen.fovy, myscreen.xyproportion, myscreen.near, myscreen.far   '' Calculate The Aspect Ratio Of The Window
    osgl_Perspective myscreen.fovy, myscreen.xyproportion, myscreen.near, myscreen.far   '' Calculate The Aspect Ratio Of The Window

'glFrustum(fLeft+offsetCamera, fRight+offsetCamera, fBottom, fTop, fNear, fFar);
    'glFrustum -320,320,240,-240,.001,10000
    'gluPerspective 45.0, 1, 0.1, 100.0   '' Calculate The Aspect Ratio Of The Window

glShadeModel GL_SMOOTH                   '' Enables Smooth Color Shading
glHint GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST
glHint GL_POLYGON_SMOOTH_HINT, GL_FASTEST
glHint GL_TEXTURE_COMPRESSION_HINT, GL_FASTEST

'glShadeModel GL_FLAT
'glHint GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST
'glHint GL_POLYGON_SMOOTH_HINT, GL_NICEST
'glHint GL_TEXTURE_COMPRESSION_HINT, GL_NICEST


'glClearColor 0.0, 0.0, 0.0, 0.0          '' Clear The Background Color To Black
glClearDepth 1.0                                   '' Enables Clearing Of The Depth Buffer
'glBlendFunc GL_SRC_ALPHA, GL_ONE         '' Select The Type Of Blending
glBlendFunc GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
glEnable GL_BLEND                                      '' Enable Blending
glEnable GL_TEXTURE_2D                   '' Enable 2D Texture Mapping
glEnable GL_ALPHA_TEST
'glAlphaFunc GL_GREATER, 0.001
glAlphaFunc GL_GREATER, 0.0
'glEnable GL_DEPTH_TEST                              '' Enables Depth Testing
glDepthFunc(GL_LESS)                                '' The Type Of Depth Test To Do

glEnable GL_COLOR_MATERIAL

           ' // Turn on antialiasing, and give hint to do the best
            '// job possible.
           ' glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
           ' glEnable(GL_BLEND);
           ' glEnable(GL_POINT_SMOOTH);
           ' glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
            'glEnable(GL_LINE_SMOOTH)
           ' glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
           ' glEnable(GL_POLYGON_SMOOTH);
            'glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);

           ' // Turn off blending and all smoothing
           ' glDisable(GL_BLEND);
           ' glDisable(GL_LINE_SMOOTH);
           ' glDisable(GL_POINT_SMOOTH);
            'glDisable(GL_POLYGON_SMOOTH);

            'glEnable(GL_POINT_SMOOTH)
           ' glHint(GL_POINT_SMOOTH_HINT, GL_NICEST)
           ' glEnable(GL_LINE_SMOOTH)
           ' glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
           ' glEnable(GL_POLYGON_SMOOTH)
           ' glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST)

'glEnable(GL_CULL_FACE)
'glCullFace(GL_FRONT_AND_BACK)

#endif

osgl_set3dcoords

'left eye
osgl_LookAt(-myscreen.eyedistance, 0, 0,      -myscreen.eyedistance,  0,  -1,          0, 1, 0)
	for i as integer=0 to 16
		osgl_lookat_matrix1(i)=osgl_lookat_matrix(i)
	next i

'right eye
osgl_LookAt(myscreen.eyedistance, 0, 0,      myscreen.eyedistance,  0,  -1,          0, 1, 0)
	dim ii as integer
	for ii=0 to 16
		osgl_lookat_matrix2(ii)=osgl_lookat_matrix(ii)
	next ii
	ii=0

'normal
osgl_LookAt(0, 0, 0,      0,  0,  0,          0, 1, 0)

osgl_set3dcoords

end sub

sub osgl_fog(byval ison as integer=0, byval density as single=0.0015, byval r as single=0,g as single=0,b as single=0)
#IFNDEF _osgl_softrender_
if ison then
	dim as single fogcolor(3)
	fogcolor(0)=r/255 : fogcolor(1)=g/255: fogcolor(2)=b/255 : fogcolor(3)=1.0
	glFogf GL_FOG_DENSITY, density
	glFogfv GL_FOG_COLOR, @fogcolor(0)
	glEnable GL_FOG
else
	glDisable GL_FOG
end if
#ENDIF
end sub

sub osgl_light(byval ison as integer=0, byval x as single=-100,byval y as single=-100,byval z as single=-100,byval w as single=0,r as ubyte=255,g as ubyte=255,b as ubyte=255,a as ubyte=255)
#IFNDEF _osgl_softrender_
if ison then
	glEnable GL_LIGHTING
	glEnable GL_LIGHT1
else
	glDisable GL_LIGHTING
	glDisable GL_LIGHT1
end if

glLightfv GL_LIGHT1,GL_SPOT_DIRECTION,@LightDirection(0)

LightDiffuse(0)=r/255:LightDiffuse(1)=g/255:LightDiffuse(2)=b/255:LightDiffuse(3)=a/255
glLightfv GL_LIGHT1, GL_DIFFUSE, @LightDiffuse(0)

LightPosition(0) = x:LightPosition(1) = y:LightPosition(2) = z:LightPosition(3) = w
glLightfv GL_LIGHT1, GL_POSITION, @LightPosition(0)

#ENDIF
end sub

declare sub osgl_FadeIndraw(byval effect as integer=0,byval a as integer=0)

declare sub osgl_Print(byval x as single=0, byval y as single=0, byval z as single=0, byval printstring as string,byval xscale as single=1,byval yscale as single=1,centered as integer=0,byval blendmode as integer=1,byval colour as uinteger=rgba(255,255,255,255),byval orientation as integer=-1, byval altfont as integer=0, byval nehefont as integer=0)




sub osgl_interframeinterval()
sleep int(myscreen.interframetime*1000),1
end sub

dim shared as any ptr osgl_interframeinterval_thread
dim shared as any ptr osgl_interframeinterval_ptr
osgl_interframeinterval_ptr=@osgl_interframeinterval

sub osgl_sync(byval forceframe as integer=0)
if osgl_ended=1 then end

'frame skip
if myscreen.frameskipon=1 then
    '0=auto 1=force on -1=force off
    if myscreen.frameskip=1 or forceframe then myscreen.frameskip=0 else myscreen.frameskip=1
    'sai antes do flip
end if

'se for usar 3D, limpa depth buffer
#IFNDEF _osgl_softrender_
if myscreen.usingdepthbuffer then glClear  GL_DEPTH_BUFFER_BIT : myscreen.usingdepthbuffer=0
#endif

myscreen.interframetimer=timer()

'count fps
myscreen.fpscounter+=1
if timer()-myscreen.fpstimer>1 then 'a cada 1 segundo
    myscreen.fpstimer=timer()
    myscreen.fps=myscreen.fpscounter
    myscreen.fpscounter=0

   'myscreen.screensaverpoketime+=1
   'if myscreen.screensaverpoketime>=50 then
'	osgl_pokescreensaver
 '  end if

    'auto frame skip
    if myscreen.frameskipmode=0 then
    if myscreen.frameskipon=0 then
    if myscreen.fps<0.8*myscreen.mysyncrate then
    myscreen.frameskipcounter+=1
    if myscreen.frameskipcounter>4 then
        myscreen.frameskipcounter=0
        myscreen.frameskipon=1
        printdebug "Screen : Too slow : Frameskip enabled!"
    end if
    else
    myscreen.frameskipcounter=0
    end if
    end if
    end if

    #ifdef _osgl_debugfps_
	printconsole "FPS="+str(myscreen.fps/(myscreen.frameskipon+1))+" frdrawn="+str(myscreen.framesdrawn)+" skip="+str(myscreen.frameskipon)+" FRE="+str(fre())
    #endif


end if

'fade in
if myscreen.FadeInalpha>0 then
    myscreen.FadeInalpha-=4*myscreen.fadeinspeed
    if myscreen.FadeInalpha<0 then myscreen.FadeInalpha=0
    osgl_FadeIndraw(myscreen.fadeineffect,myscreen.FadeInalpha)
end if

'fps
if myscreen.debugfps then
if myscreen.virgin then
	osgl_print(-myscreen.x/2+12,-myscreen.y/2+10,-10,str(myscreen.fps/(myscreen.frameskipon+1)),1.0,1.0,0,-1,rgba(255,255,255,128))
end if
end if


'control time interval between frames
if myscreen.mysyncrate then
if myscreen.vsync=0 or myscreen.fps>myscreen.maxsyncrate or myscreen.monitorrefresh>myscreen.maxsyncrate or myscreen.trustvsync=0 then  'não precisa dormir se o vsync estiver ligado e adequado a fps

	'Espera vsync conforme o caso e atualiza a tela
	select case as const myscreen.syncmode
	case 1
        screensync
	case 2
		if osgl_interframeinterval_thread then ThreadWait(osgl_interframeinterval_thread)
		osgl_interframeinterval_thread=ThreadCreate(osgl_interframeinterval_ptr)
	case else
		while (Timer()<myscreen.interframetime2) and Timer()>.1
			if myscreen.cansleep then
				if myscreen.sleepframe=0 then sleep 1,1
				myscreen.sleepframe+=1
				if myscreen.sleepframe>4 then myscreen.sleepframe=0
			end if
			'The accuracy of Sleep is variable depending on the OS cycle time (Windows NT/2K/XP: 15 ms, 9x/Me: 50 ms, Linux 10ms, DOS 55 ms).
		wend
	end select

end if
end if

'glFlush

if myscreen.frameskip=0 then
if myscreen.virgin=0 then
	'se não desenhou nada novo desde o ultimo flip, não troca os buffers
	'sleep 1,1
	screensync 'dorme um pouco se não há nada pra renderizar (simula o tempo de 1 frame)
else
	'draw our stuff
	if myscreen.useopengl then flip else ScreenCopy 1,0 'swap buffers FLIP  FLIP  FLIP  FLIP  FLIP  FLIP  FLIP  FLIP  FLIP  FLIP  FLIP  FLIP  FLIP  FLIP  FLIP  FLIP
	myscreen.virgin=0
end if
end if

myscreen.interframetime2=timer()+myscreen.interframetime

osgl_framedrawn=1
myscreen.framesdrawn+=1

osgl_pollmouse()

'osgl_pollosevents
'if osgl_pollinput_thread then ThreadWait(osgl_pollinput_thread) else osgl_pollinput
'osgl_pollinput_thread=ThreadCreate(osgl_pollinput_ptr)
osgl_pollinput()
osgl_pollinput_keyboard()

'osgl_pollinput
end sub

function osgl_fps() as integer
return myscreen.fps/(myscreen.frameskipon+1)
end function

sub osgl_mousehide
myscreen.mouseinactive=_osgl_mousetimeout
myscreen.mouseclip=1
end sub

sub osgl_mousetouchscreen(byval tsmode as integer=0)
	select case tsmode
		case 0: myscreen.mousetouchscreen=0
		case else: myscreen.mousetouchscreen=1
	end select
end sub

function osgl_mousex as integer
function=myscreen.mousex
end function

function osgl_mousey as integer
function=-myscreen.mousey
end function

function osgl_mousez as integer
function=myscreen.mousez
end function

function osgl_mousewheel as integer
dim as integer tmp=(myscreen.mousezold-myscreen.mousez)
if abs(tmp)>200 then tmp=-sgn(tmp)
function=tmp
end function

function osgl_mouseclip as integer
if myscreen.mouseinactive>=_osgl_mousetimeout then myscreen.mouseclip=1
function=myscreen.mouseclip
end function

function osgl_mousebutton(byval i as integer=-1) as integer
dim as integer retval
if myscreen.mouseclip or myscreen.mousebuttons=0 then
	retval=0
else
	retval=myscreen.mousebtn(i)
	'myscreen.mousebtn(i)=2
	if retval<>0 then
		if myscreen.mousebtn(i)=0 then myscreen.mousebtn(i)=1 else myscreen.mousebtn(i)=2
	end if
end if
function=retval
end function

dim shared as integer _osgl_menumovesound=0,_osgl_menuclicksound=0,_osgl_menuplayer=1

sub osgl_waitkeyrelease
osgl_clearkeyboardbuffer()
'osgl_syncbuffers
dim as integer ii=0, anykey=0
do

    osgl_sync
    osgl_pollosevents 'poll events

	ii+=1
	for kkk1 as integer=1 to 254
		if multikey(kkk1) then
			anykey=1
			exit for
		end if
	next kkk1

loop until (anykey=0 and osgl_button=0 and osgl_button(_osgl_menuplayer)=0 and osgl_mousebutton=0 and osgl_enterkey=0 and osgl_esckey=0) or (ii>15)
myscreen.frameskipcounter=0
end sub


sub osgl_keypause
osgl_waitkeyrelease
dim as integer anykey=0

do

    osgl_sync()
    osgl_pollosevents 'poll events

	for kkk1 as integer=1 to 254
		if multikey(kkk1) then
			anykey=1
			exit for
		end if
	next kkk1
	
loop until anykey or osgl_button or osgl_mousebutton

myscreen.frameskipcounter=0
osgl_waitkeyrelease
end sub


sub osgl_delay(byval numframes as uinteger)
'osgl_syncbuffers
for i as integer=0 to numframes-1
    osgl_pollosevents
    osgl_sync
next i
myscreen.frameskipcounter=0
end sub

'    ROTOZOOM
Sub rotozoom( Byref dst As FBIMAGE Ptr = 0, Byref src As Const FBIMAGE Ptr, Byval positx As Integer, Byval posity As Integer, Byref angle As Integer, Byref zoomx As Single, Byref zoomy As Single = 0, Byval transcol As Uinteger  = &hffff00ff, Byval offsetx As Integer = 0, Byref offsety As Integer = 0 )
#if __FB_LANG__="fb"

    'Rotozoom for 32-bit FBImage by Dr_D(Dave Stanley) and yetifoot(Simon Nash)
    'No warranty implied... use at your own risk ;)

    Static As Integer mx, my, col, nx, ny
    Static As Single nxtc, nxts, nytc, nyts
    Static As Single tcdzx, tcdzy, tsdzx, tsdzy
    Static As Integer sw2, sh2, dw, dh
    Static As Single tc, ts, _mx, _my
    Static As Uinteger Ptr dstptr, srcptr, odstptr
    Static As Integer xput, yput, startx, endx, starty, endy
    Static As Integer x(3), y(3), xa, xb, ya, yb, lx, ly
    Static As Ubyte Ptr srcbyteptr, dstbyteptr
    Static As Integer dstpitch, srcpitch, srcbpp, dstbpp, srcwidth, srcheight

    If zoomx = 0 Then Exit Sub
    If zoomy = 0 Then zoomy = zoomx
    If src = 0 Then Exit Sub

    If dst = 0 Then
        dstptr = screenptr
        odstptr = dstptr
        screeninfo dw,dh,,,dstpitch
    Else
        dstptr = cast( Uinteger Ptr, dst + 1 )
        odstptr = cast( Uinteger Ptr, dst + 1 )
        dw = dst->width
        dh = dst->height
        dstbpp = dst->bpp
        dstpitch = dst->pitch
    End If

    srcptr = cast( Uinteger Ptr, src + 1 )
    srcbyteptr = cast( Ubyte Ptr, srcptr )
    dstbyteptr = cast( Ubyte Ptr, dstptr )

    sw2 = src->width\2
    sh2 = src->height\2
    srcbpp = src->bpp
    srcpitch = src->pitch
    srcwidth = src->width
    srcheight = src->height

    tc = Cos( angle * pi_180 )
    ts = Sin( angle * pi_180 )
    tcdzx = tc/zoomx
    tcdzy = tc/zoomy
    tsdzx = ts/zoomx
    tsdzy = ts/zoomy

    xa = sw2 * tc * zoomx + sh2  * ts * zoomx
    ya = sh2 * tc * zoomy - sw2  * ts * zoomy

    xb = sh2 * ts * zoomx - sw2  * tc * zoomx
    yb = sw2 * ts * zoomy + sh2  * tc * zoomy

    Dim As Integer centerx = -(offsetx*(tc*zoomx) + offsety*(ts*zoomx)) + offsetx
    Dim As Integer centery = -(offsety*(tc*zoomy) - offsetx*(ts*zoomy)) + offsety

    x(0) = sw2-xa
    x(1) = sw2+xa
    x(2) = sw2-xb
    x(3) = sw2+xb
    y(0) = sh2-ya
    y(1) = sh2+ya
    y(2) = sh2-yb
    y(3) = sh2+yb

    For i As Integer = 0 To 3
        For j As Integer = i To 3
            If x(i)>=x(j) Then
                Swap x(i), x(j)
            End If
        Next
    Next
    startx = x(0)
    endx = x(3)

    For i As Integer = 0 To 3
        For j As Integer = i To 3
            If y(i)>=y(j) Then
                Swap y(i), y(j)
            End If
        Next
    Next
    starty = y(0)
    endy = y(3)

    positx-=sw2
    posity-=sh2
    positx+=centerx
    posity+=centery
    If posity+starty<0 Then starty = -posity
    If positx+startx<0 Then startx = -positx
    If posity+endy<0 Then endy = -posity
    If positx+endx<0 Then endx = -positx

    If positx+startx>(dw-1) Then startx = (dw-1)-positx
    If posity+starty>(dh-1) Then starty = (dh-1)-posity
    If positx+endx>(dw-1) Then endx = (dw-1)-positx
    If posity+endy>(dh-1) Then endy = (dh-1)-posity
    If startx = endx Or starty = endy Then Exit Sub


    xput = (startx + positx) * 4
    yput = starty + posity
    ny = starty - sh2
    nx = startx - sw2
    nxtc = (nx * tcdzx)
    nxts = (nx * tsdzx)
    nytc = (ny * tcdzy)
    nyts = (ny * tsdzy)
    dstptr += dstpitch * yput \ 4

        Dim As Integer y_draw_len = (endy - starty) + 1
        Dim As Integer x_draw_len = (endx - startx) + 1


	#IFNDEF __FB_GCC__
    'and we're off!
    asm
        mov edx, dword Ptr [y_draw_len]

        test edx, edx ' 0?
        jz y_end      ' nothing to do here

        fld dword Ptr[tcdzy]
        fld dword Ptr[tsdzy]
        fld dword Ptr [tcdzx]
        fld dword Ptr [tsdzx]

        y_inner:

        fld dword Ptr[nxtc]     'st(0) = nxtc, st(1) = tsdzx, st(2) = tcdzx, st(3) = tsdzy, st(4) = tcdzy
        fsub dword Ptr[nyts]    'nxtc-nyts
        fiadd dword Ptr[sw2]    'nxtc-nyts+sw2

        fld dword Ptr[nxts]     'st(0) = nxts, st(1) = tsdzx, st(2) = tcdzx, st(3) = tsdzy, st(4) = tcdzy
        fadd dword Ptr[nytc]    'nytc+nxts
        fiadd dword Ptr[sh2]    'nxts+nytc+sh2
        'fpu stack returns to: st(0) = tsdzx, st(1) = tcdzx, st(2) = tsdzy, st(3) = tcdzy

        mov ebx, [xput]
        add ebx, [dstptr]

        mov ecx, dword Ptr [x_draw_len]

        test ecx, ecx ' 0?
        jz x_end      ' nothing to do here

        x_inner:

        fist dword Ptr [my] ' my = _my

        fld st(1)           ' mx = _mx
        fistp dword Ptr [mx]

        mov esi, dword Ptr [mx]         ' esi = mx
        mov edi, dword Ptr [my]         ' edi = my

        ' bounds checking
        test esi, esi       'mx<0?
        js no_draw
        'mov esi, 0

        test edi, edi
        'mov edi, 0
        js no_draw          'my<0?

        cmp esi, dword Ptr [srcwidth]   ' mx >= width?
        jge no_draw
        cmp edi, dword Ptr [srcheight]  ' my >= height?
        jge no_draw

        ' calculate position in src buffer
        mov eax, dword Ptr [srcbyteptr] ' eax = srcbyteptr
        imul edi, dword Ptr [srcpitch]  ' edi = my * srcpitch
        add eax, edi
        Shl esi, 2
        ' eax becomes src pixel color
        mov eax, dword Ptr [eax+esi]
        cmp eax, [transcol]
        je no_draw

        ' draw pixel
        mov dword Ptr [ebx], eax
        no_draw:

        fld st(3)
        faddp st(2), st(0) ' _mx += tcdzx
        fadd st(0), st(2) ' _my += tsdzx

        ' increment the output pointer
        add ebx, 4

        ' increment the x loop
        dec ecx
        jnz x_inner

        x_end:

        fstp dword Ptr [_my]
        fstp dword Ptr [_mx]

        'st(0) = tsdzx, st(1) = tcdzx, st(2) = tsdzy, st(3) = tcdzy
        'nytc += tcdzy
        fld dword Ptr[nytc]
        fadd st(0), st(4)
        fstp dword Ptr[nytc]

        'st(0) = tsdzx, st(1) = tcdzx, st(2) = tsdzy, st(3) = tcdzy
        'nyts+=tsdzy
        fld dword Ptr[nyts]
        fadd st(0), st(3)
        fstp dword Ptr[nyts]

        'dstptr += dst->pitch
        mov eax, dword Ptr [dstpitch]
        add dword Ptr [dstptr], eax

        dec edx
        jnz y_inner

        y_end:

        finit
    End asm
    #ENDIF

#endif
End Sub


'MULTIPUT
' MultiPut [destination],[xmidpos],[ymidpos],source,[xScale],[yScale],[rotate],[mirror],[flipp],[Trans],[Custom],[Param]

'#define UseRad 'if not then Rotate are in degrees

Sub MultiPut(Byval lpTarget As Any Ptr= 0, _
             Byval xMidPos  As Integer= 0, _
             Byval yMidPos  As Integer= 0, _
             Byval lpSource As Any Ptr   , _
             Byval xScale   As Single = 1, _
             Byval yScale   As Single = 1, _
             Byval Rotate   As Single = 0, _
             Byval mirror   As Integer = 0, _
             Byval Flipp   As Integer = 0, _
             Byval Trans    As Integer= 0, _
             Byval Custom As Function(Byval Src As Uinteger, Byval Dest As Uinteger, Byval Param As Any Ptr = 0) As Uinteger = 0, _
             Byval Param As Any Ptr = 0)

  If (screenptr=0) Or (lpSource=0) Then Exit Sub

  If xScale < 0.001 Then xScale=0.001
  If yScale < 0.001 Then yScale=0.001

  Dim As Integer MustLock,MustRotate

  If lpTarget= 0 Then MustLock  =1
  If Rotate  <>0 Then MustRotate=1

  Dim As Integer  TargetWidth,TargetHeight,TargetBytes,TargetPitch
  If MustLock Then
    screeninfo    _
    TargetWidth , _
    TargetHeight, _
    TargetBytes ,,_
    TargetPitch
    TargetBytes Shr=3

    lpTarget=screenptr
  Else
    TargetBytes  = cptr(Uinteger Ptr,lpTarget)[1]
    TargetWidth  = cptr(Uinteger Ptr,lpTarget)[2]
    TargetHeight = cptr(Uinteger Ptr,lpTarget)[3]
    TargetPitch  = cptr(Uinteger Ptr,lpTarget)[4]
    lpTarget    += 32
  End If
  If (TargetWidth<4) Or (TargetHeight<4) Then Exit Sub

  Dim As Integer   SourceWidth,SourceHeight,SourceBytes,SourcePitch
  If cptr(Integer Ptr,lpSource)[0] = 7 Then
    SourceBytes  = cptr(Uinteger Ptr,lpSource)[1]
    SourceWidth  = cptr(Uinteger Ptr,lpSource)[2]
    SourceHeight = cptr(Uinteger Ptr,lpSource)[3]
    SourcePitch  = cptr(Uinteger Ptr,lpSource)[4]
    lpSource    += 32
  Else
    SourceBytes  = cptr(Ushort Ptr,lpSource)[0] And 7
    SourceWidth  = cptr(Ushort Ptr,lpSource)[0] Shr 3
    SourceHeight = cptr(Ushort Ptr,lpSource)[1]
    SourcePitch  = SourceWidth * SourceBytes
    lpSource    += 4
  End If
#if 0
  ? TargetWidth & "x" & TargetHeight & "x" & TargetBytes,TargetPitch
  ? SourceWidth & "x" & SourceHeight & "x" & SourceBytes,SourcePitch
  ? MustLock,Trans
  'Sleep:End
#endif

  If (SourceWidth<2) Or (SourceHeight<2) Then Exit Sub
  If (TargetBytes<>SourceBytes) Then Exit Sub

#define xs 0 'screen
#define ys 1
#define xt 2 'texture
#define yt 3
  Dim As Single Points(3,3)
  points(0,xs)=-SourceWidth/2 * xScale
  points(1,xs)= SourceWidth/2 * xScale
  points(2,xs)= points(1,xs)
  points(3,xs)= points(0,xs)

  points(0,ys)=-SourceHeight/2 * yScale
  points(1,ys)= points(0,ys)
  points(2,ys)= SourceHeight/2 * yScale
  points(3,ys)= points(2,ys)

  points(1,xt)= SourceWidth-1
  points(2,xt)= points(1,xt)
  points(2,yt)= SourceHeight-1
  points(3,yt)= points(2,yt)

if mirror then swap points(0,xt),points(1,xt) :swap points(2,xt),points(3,xt)
if Flipp then swap points(0,yt),points(3,yt) :swap points(2,yt),points(1,yt)
'if mirror then swap points(1,xt),points(2,xt)
'if Flipp then swap points(2,yt),points(3,yt)


  Dim As Uinteger i
  Dim As Single x,y
  If MustRotate Then
    #ifndef UseRad
    Rotate*=Atn(1)/45 'degree 2 rad
    #endif
    While Rotate< 0       :rotate+=8*Atn(1):Wend
    While Rotate>=8*Atn(1):rotate-=8*Atn(1):Wend
    For i=0 To 3
      x=points(i,xs)*Cos(Rotate) - points(i,ys)*Sin(Rotate)
      y=points(i,xs)*Sin(Rotate) + points(i,ys)*Cos(Rotate)
      points(i,xs)=x:points(i,ys)=y
    Next
  End If

  Dim As Integer yStart,yEnd,xStart,xEnd
  yStart=100000:yEnd=-yStart:xStart=yStart:xEnd=yEnd

#define LI 0   'LeftIndex
#define RI 1   'RightIndex
#define  IND 0 'Index
#define NIND 1 'NextIndex
  Dim As Integer CNS(1,1) 'Counters

  For i=0 To 3
    points(i,xs)=Int(points(i,xs)+xMidPos)
    points(i,ys)=Int(points(i,ys)+yMidPos)
    If points(i,ys)<yStart Then yStart=points(i,ys):CNS(LI,IND)=i
    If points(i,ys)>yEnd   Then yEnd  =points(i,ys)
    If points(i,xs)<xStart Then xStart=points(i,xs)
    If points(i,xs)>xEnd   Then xEnd  =points(i,xs)
  Next
  If yStart =yEnd         Then Exit Sub
  If yStart>=TargetHeight Then Exit Sub
  If yEnd   <0            Then Exit Sub
  If xStart = xEnd        Then Exit Sub
  If xStart>=TargetWidth  Then Exit Sub
  If xEnd   <0            Then Exit Sub

  Dim As Ubyte    Ptr t1,s1
  Dim As Ushort   Ptr t2,s2
  Dim As Uinteger     t2c, s2c
  Dim As Uinteger Ptr t4,s4


#define ADDD 0
#define CMP 1
#define SET 2
  Dim As Integer ACS(1,2) 'add compare and set
  ACS(LI,ADDD)=-1:ACS(LI,CMP)=-1:ACS(LI,SET)=3
  ACS(RI,ADDD)= 1:ACS(RI,CMP)= 4:ACS(RI,SET)=0


#define EX  0
#define EU  1
#define EV  2
#define EXS 3
#define EUS 4
#define EVS 5
  Dim As Single E(2,6),S(6),Length,uSlope,vSlope
  Dim As Integer U,UV,UA,UN,V,VV,VA,VN

  ' share the same highest point
  CNS(RI,IND)=CNS(LI,IND)
  If MustLock Then screenlock
  ' loop from Top to Bottom
  While yStart<yEnd
    'Scan Left and Right sides together
    For i=LI To RI
      ' bad to read but fast and short ;-)
      If yStart=points(CNS(i,IND),ys) Then
        CNS(i,NIND)=CNS(i,IND)+ACS(i,Addd)
        If CNS(i,NIND)=ACS(i,CMP) Then CNS(i,NIND)=ACS(i,SET)
        While points(CNS(i,IND),ys) = points(CNS(i,NIND),ys)
          CNS(i, IND)=CNS(i,NIND)
          CNS(i,NIND)=CNS(i, IND)+ACS(i,Addd)
          If CNS(i,NIND)=ACS(i,CMP) Then CNS(i,NIND)=ACS(i,SET)
        Wend
        E(i,EX) = points(CNS(i, IND),xs)
        E(i,EU) = points(CNS(i, IND),xt)
        E(i,EV) = points(CNS(i, IND),yt)
        Length  = points(CNS(i,NIND),ys)
        Length -= points(CNS(i, IND),ys)
        If Length <> 0.0 Then
          E(i,EXS) = points(CNS(i, NIND),xs)-E(i,EX):E(i,EXS)/=Length
          E(i,EUS) = points(CNS(i, NIND),xt)-E(i,EU):E(i,EUS)/=Length
          E(i,EVS) = points(CNS(i, NIND),yt)-E(i,EV):E(i,EVS)/=Length
        End If
        CNS(i,IND)=CNS(i,NIND)
      End If
    Next

    If (yStart<0)                              Then Goto SkipScanLine
    xStart=E(LI,EX)+0.5:If xStart>=TargetWidth Then Goto SkipScanLine
    xEnd  =E(RI,EX)-0.5:If xEnd  < 0           Then Goto SkipScanLine
    If (xStart=xEnd)                           Then Goto SkipScanLine
    'if xEnd  <xStart                           then goto SkipScanLine
    Length=xEnd-xStart
    uSlope=E(RI,EU)-E(LI,EU):uSlope/=Length
    vSlope=E(RI,EV)-E(LI,EV):vSlope/=Length
    If xstart<0 Then
      Length=Abs(xStart)
      U=Int(E(LI,EU)+uSlope*Length)
      V=Int(E(LI,EV)+vSlope*Length)
      xStart = 0
    Else
      U=Int(E(LI,EU)):V=Int(E(LI,EV))
    End If
    If xEnd>=TargetWidth Then xEnd=TargetWidth-1
    UV=Int(uSlope):UA=(uSlope-UV)*100000:UN=0
    VV=Int(vSlope):VA=(vSlope-VV)*100000:VN=0
    xEnd-=xStart
    Select Case TargetBytes
      Case 1
        t1=cptr(Ubyte Ptr,lpTarget)
        t1+=yStart*TargetPitch+xStart:xStart=0
        If Custom Then
          While xStart<xEnd
            s1=lpSource+V*SourcePitch+U
            *t1=Custom(*s1,*t1,Param)
            U+=UV:UN+=UA:If UN>=100000 Then U+=1:UN-=100000
            V+=VV:VN+=VA:If VN>=100000 Then V+=1:VN-=100000
            If u<0 Then u=0
            If v<0 Then v=0
            xStart+=1:t1+=1
          Wend
        Elseif Trans=0 Then
          While xStart<xEnd
            s1=lpSource+V*SourcePitch+U
            *t1=*s1
            U+=UV:UN+=UA:If UN>=100000 Then U+=1:UN-=100000
            V+=VV:VN+=VA:If VN>=100000 Then V+=1:VN-=100000
            If u<0 Then u=0
            If v<0 Then v=0
            xStart+=1:t1+=1
          Wend
        Else
          While xStart<xEnd
            s1=lpSource+V*SourcePitch+U
            If *s1 Then *t1=*s1
            U+=UV:UN+=UA:If UN>=100000 Then U+=1:UN-=100000
            V+=VV:VN+=VA:If VN>=100000 Then V+=1:VN-=100000
            If u<0 Then u=0
            If v<0 Then v=0
            xStart+=1:t1+=1
          Wend
        End If
      Case 2
        t2=cptr(Short Ptr,lpTarget)
        t2+=yStart*(TargetPitch Shr 1)+xStart:xStart=0
        If Custom Then
          While xStart<xEnd
            s2=cptr(Short Ptr,lpSource)+V*(SourcePitch Shr 1)+U
            s2c=*s2
            t2c=*t2
            s2c=(s2c And &H001F) Shl 3 Or (s2c Shr 2 And &H000007) Or _
                (s2c And &H07E0) Shl 5 Or (s2c Shr 1 And &H000300) Or _
                (s2c And &HF800) Shl 8 Or (s2c Shl 3 And &H070000) Or &HFF000000
            t2c=(t2c And &H001F) Shl 3 Or (s2c Shr 2 And &H000007) Or _
                (t2c And &H07E0) Shl 5 Or (s2c Shr 1 And &H000300) Or _
                (t2c And &HF800) Shl 8 Or (s2c Shl 3 And &H070000) Or &HFF000000
            t2c=Custom(s2c,t2c,Param)
            *t2=(t2c Shr 3 And &H001F) Or _
                (t2c Shr 5 And &H07E0) Or _
                (t2c Shr 8 And &HF800)
            U+=UV:UN+=UA:If UN>=100000 Then U+=1:UN-=100000
            V+=VV:VN+=VA:If VN>=100000 Then V+=1:VN-=100000
            If u<0 Then u=0
            If v<0 Then v=0
            xStart+=1:t2+=1
          Wend
        Elseif Trans=0 Then
          While xStart<xEnd
            s2=cptr(Short Ptr,lpSource)+V*(SourcePitch Shr 1)+U
            *t2=*s2
            U+=UV:UN+=UA:If UN>=100000 Then U+=1:UN-=100000
            V+=VV:VN+=VA:If VN>=100000 Then V+=1:VN-=100000
            If u<0 Then u=0
            If v<0 Then v=0
            xStart+=1:t2+=1
          Wend
        Else
          While xStart<xEnd
            s2=cptr(Short Ptr,lpSource)+V*(SourcePitch Shr 1)+U
            If *s2<>&HF81F Then *t2=*s2
            U+=UV:UN+=UA:If UN>=100000 Then U+=1:UN-=100000
            V+=VV:VN+=VA:If VN>=100000 Then V+=1:VN-=100000
            If u<0 Then u=0
            If v<0 Then v=0
            xStart+=1:t2+=1
          Wend
        End If
      Case 4
        t4=cptr(Integer Ptr,lpTarget)+yStart*(TargetPitch Shr 2)+xStart:xStart=0
        If Custom Then
          While xStart<xEnd
            s4=cptr(Integer Ptr,lpSource)+V*(SourcePitch Shr 2)+U
            *t4=Custom(*s4, *t4, Param)
            U+=UV:UN+=UA:If UN>=100000 Then U+=1:UN-=100000
            V+=VV:VN+=VA:If VN>=100000 Then V+=1:VN-=100000
            If u<0 Then u=0
            If v<0 Then v=0
            xStart+=1:t4+=1
          Wend
        Elseif Trans=0 Then
          While xStart<xEnd
            s4=cptr(Integer Ptr,lpSource)+V*(SourcePitch Shr 2)+U
            *t4=*s4
            U+=UV:UN+=UA:If UN>=100000 Then U+=1:UN-=100000
            V+=VV:VN+=VA:If VN>=100000 Then V+=1:VN-=100000
            If u<0 Then u=0
            If v<0 Then v=0
            xStart+=1:t4+=1
          Wend
        Else
          While xStart<xEnd
            's4=cptr(Integer Ptr,lpSource):s4+=V*(SourcePitch shr 2):s4+=U
            s4=cptr(Integer Ptr,lpSource)+V*(SourcePitch Shr 2)+U
            If (*s4 And &HFFFFFF)<>&HFF00FF Then *t4=*s4
            U+=UV:UN+=UA:If UN>=100000 Then U+=1:UN-=100000
            V+=VV:VN+=VA:If VN>=100000 Then V+=1:VN-=100000
            If u<0 Then u=0
            If v<0 Then v=0
            xStart+=1:t4+=1
          Wend
        End If
    End Select

SkipScanLine:
    E(LI,EX)+=E(LI,EXS):E(LI,EU)+=E(LI,EUS):E(LI,EV)+=E(LI,EVS)
    E(RI,EX)+=E(RI,EXS):E(RI,EU)+=E(RI,EUS):E(RI,EV)+=E(RI,EVS)
    yStart+=1:If yStart=TargetHeight Then yStart=yEnd 'exit loop
  Wend
If MustLock Then screenunlock
End Sub

Function Trans(Byval Src As Uinteger, Byval Dest As Uinteger, Byval Param As Any Ptr = 0) As Uinteger

    If (Src And &HFFFFFF) = &HFF00FF Then Return Dest Else Return Src

End Function

Function Trans2(Byval Src As Uinteger, Byval Dest As Uinteger, Byval Param As Any Ptr = 0) As Uinteger

    If (Src And &HFFFFFFFF) = &H00000000 Then Return Dest Else Return Src

End Function

'scale2x
'  A    --\ 1 2
'C P B  --/ 3 4
'  D
 '1=P; 2=P; 3=P; 4=P;
 'IF C==A AND C!=D AND A!=B => 1=A
 'IF A==B AND A!=C AND B!=D => 2=B
 'IF B==D AND B!=A AND D!=C => 4=D
 'IF D==C AND D!=B AND C!=A => 3=C

'eagle
'first:        |Then
'. . . --\ CC  |S T U  --\ 1 2
'. C . --/ CC  |V C W  --/ 3 4
'. . .         |X Y Z
'              | IF V==S==T => 1=S
'              | IF T==U==W => 2=U
'              | IF V==X==Y => 3=X
'              | IF W==Z==Y => 4=Z

function osgl_copyimage(byval src as any ptr) as any ptr
dim as integer x,y
ImageInfo src,x,y
dim dest as any ptr=imagecreate(x,y)
put dest,(0,0),src,pset
return dest
end function

sub osgl_imageRGBA2BGRA(byval buffer as any ptr)
    'troca RGB->BGR
    dim as integer x,y
    Dim As uByte Ptr pByte
    ImageInfo buffer,x,y,,,pByte
    Dim As Integer TextSize = (x * y * 4)
    'textsize-1 ou textsize? is it corrupting the heap?
    For i As Integer = 0 To TextSize-1 Step 4
        Swap *(pByte+i), *(pByte+i+2)
    Next i
end sub



Sub ImageEagle__ overload (Byref src As FBImage Ptr,byref dst as FBImage ptr)
#if __FB_LANG__="fb"

'eagle
'first:        |Then
'. . . --\ CC  |S T U  --\ 1 2
'. C . --/ CC  |V C W  --/ 3 4
'. . .         |X Y Z
'              | IF V==S==T => 1=S
'              | IF T==U==W => 2=U
'              | IF V==X==Y => 3=X
'              | IF W==Z==Y => 4=Z


        Dim As Integer xx = src->Width,yy = src->Height
        Dim As Integer pitch1= src->pitch
   ' dim as FBImage ptr dst=imagecreate(xx*2,yy*2,,32)
    if dst=0 then dst=imagecreate(xx*2,yy*2,,32)
        Dim As Integer x2= dst->Width,y2= dst->Height
        Dim As Integer pitch= dst->pitch
        Dim As Uinteger Ptr srcpixels = CPtr( Uinteger Ptr, CPtr( FBIMAGE Ptr, src + 1 ) )
        Dim As Uinteger Ptr destpixels= CPtr( Uinteger Ptr, CPtr( FBIMAGE Ptr, dst + 1 ) )
        'Dim As Uinteger A,B,C,D,P
        Dim As Uinteger S,T,U,V,C,W,X,Y,Z
        'result = ImageInfo ( [width] [, [height] [, [bypp] [, [pitch] [, [pixdata] [, [imgsize]]]]]] )
        'imageinfo buffer,x,y,,,srcpixels
        'Dim buffer2 As FBImage Ptr=imagecreate(x*2,y*2,,32)
        'imageinfo buffer2,x2,y2,,,destpixels

	dim as integer pitch4, pitch14, i2, j2
	'pitch4=pitch*4
	'pitch14=pitch1*4

    For j As Integer=0 To yy-1
    For i As Integer=0 To xx-1
		'i2=i+i
		'j2=j+j
        C=srcpixels[i+j*xx]
        destpixels[i*2+j*2*pitch*4]=C
        destpixels[i*2+1+j*2*pitch*4]=C
        destpixels[i*2+j*2*pitch*4+pitch*4]=C
        destpixels[i*2+1+j*2*pitch*4+pitch*4]=C
    Next i
    Next j

    For j As Integer=1 To yy-2
    For i As Integer=1 To xx-2

'        C=srcpixels[i+j*pitch1*4]
'        S=srcpixels[i-1+(j-1)*pitch1*4]
'        T=srcpixels[i+(j-1)*pitch1*4]
'        U=srcpixels[i+1+(j-1)*pitch1*4]
'        V=srcpixels[i-1+j*pitch1*4]
'        W=srcpixels[i+1+j*pitch1*4]
'        X=srcpixels[i-1+(j+1)*pitch1*4]
'        Y=srcpixels[i+(j+1)*pitch1*4]
'        Z=srcpixels[i+1+(j+1)*pitch1*4]

'              | IF V==S==T => 1=S
'              | IF T==U==W => 2=U
'              | IF V==X==Y => 3=X
'              | IF W==Z==Y => 4=Z
	'i2=i+i
	'j2=j+j

    if V=S then
		if S=T then destpixels[i*2+j*2*pitch*4]=S
	end if

    if T=U then
		if U=W then destpixels[i*2+1+j*2*pitch*4]=U
	end if

    if V=X then
		if X=Y then destpixels[i*2+j*2*pitch*4+pitch*4]=X
	end if

    if W=Z then
		if Z=Y then destpixels[i*2+1+j*2*pitch*4+pitch*4]=Z
	end if

        'A=srcpixels[i+(j-1)*xx]
        'B=srcpixels[i+1+j*xx]
        'C=srcpixels[i-1+j*xx]
        'D=srcpixels[i+(j+1)*xx]

        'If C=A And C<>D And A<>B Then destpixels[i*2+j*2*x2]=A
        'If A=B And A<>C And B<>D Then destpixels[i*2+1+j*2*x2]=B
        'If B=D And B<>A And D<>C Then destpixels[i*2+1+j*2*x2+x2]=D
        'If D=C And D<>B And C<>A Then destpixels[i*2+j*2*x2+x2]=C


    Next i
    Next j
    'if src then imagedestroy src
    'src=dst

#endif
End Sub


Sub ImageEagle overload (Byref src As FBImage Ptr,byref dst as FBImage ptr)
#if __FB_LANG__="fb"

'eagle
'first:        |Then
'. . . --\ CC  |S T U  --\ 1 2
'. C . --/ CC  |V C W  --/ 3 4
'. . .         |X Y Z
'              | IF V==S==T => 1=S
'              | IF T==U==W => 2=U
'              | IF V==X==Y => 3=X
'              | IF W==Z==Y => 4=Z


        Dim As Integer xx = src->Width,yy = src->Height
        Dim As Integer pitch1= src->pitch
		dim as integer pitch14=pitch1/4
   ' dim as FBImage ptr dst=imagecreate(xx*2,yy*2,,32)
    if dst=0 then dst=imagecreate(xx*2,yy*2,,32)
        Dim As Integer x2= dst->Width,y2= dst->Height
        Dim As Integer pitch= dst->pitch
		dim as integer pitch4=pitch/4
        Dim As Uinteger Ptr srcpixels = CPtr( Uinteger Ptr, CPtr( FBIMAGE Ptr, src + 1 ) )
        Dim As Uinteger Ptr destpixels= CPtr( Uinteger Ptr, CPtr( FBIMAGE Ptr, dst + 1 ) )
        'Dim As Uinteger A,B,C,D,P
        Dim As Uinteger S,T,U,V,C,W,X,Y,Z
        'result = ImageInfo ( [width] [, [height] [, [bypp] [, [pitch] [, [pixdata] [, [imgsize]]]]]] )
        'imageinfo buffer,x,y,,,srcpixels
        'Dim buffer2 As FBImage Ptr=imagecreate(x*2,y*2,,32)
        'imageinfo buffer2,x2,y2,,,destpixels

		dim as integer i2, j2, j2pitch4, jpitch14, jppitch14, jmpitch14

    For j As Integer=0 To yy-1
    For i As Integer=0 To xx-1

		i2=i*2
		j2=j*2
		j2pitch4=j2*pitch4

        C=srcpixels[i+j*xx]

        destpixels[i2+j2pitch4]=C
        destpixels[i2+1+j2pitch4]=C
        destpixels[i2+j2pitch4+pitch4]=C
        destpixels[i2+1+j2pitch4+pitch4]=C

    Next i
    Next j

    For j As Integer=1 To yy-2
    For i As Integer=1 To xx-2

		jpitch14=j*pitch14
		jppitch14=(j+1)*pitch14
		jmpitch14=(j-1)*pitch14

        C=srcpixels[i+jpitch14]
        S=srcpixels[i-1+jmpitch14]
        T=srcpixels[i+jmpitch14]
        U=srcpixels[i+1+jmpitch14]
        V=srcpixels[i-1+jpitch14]
        W=srcpixels[i+1+jpitch14]
        X=srcpixels[i-1+jppitch14]
        Y=srcpixels[i+jppitch14]
        Z=srcpixels[i+1+jppitch14]

'              | IF V==S==T => 1=S
'              | IF T==U==W => 2=U
'              | IF V==X==Y => 3=X
'              | IF W==Z==Y => 4=Z
		i2=i*2
		j2=j*2
		j2pitch4=j2*pitch4

    if V=S then
		if S=T then destpixels[i2+j2pitch4]=S
	end if

    if T=U then
		if U=W then destpixels[i2+1+j2pitch4]=U
	end if

    if V=X then
		if X=Y then destpixels[i2+j2pitch4+pitch4]=X
	end if

    if W=Z then
		if Z=Y then destpixels[i2+1+j2pitch4+pitch4]=Z
	end if


        'A=srcpixels[i+(j-1)*xx]
        'B=srcpixels[i+1+j*xx]
        'C=srcpixels[i-1+j*xx]
        'D=srcpixels[i+(j+1)*xx]

        'If C=A And C<>D And A<>B Then destpixels[i*2+j*2*x2]=A
        'If A=B And A<>C And B<>D Then destpixels[i*2+1+j*2*x2]=B
        'If B=D And B<>A And D<>C Then destpixels[i*2+1+j*2*x2+x2]=D
        'If D=C And D<>B And C<>A Then destpixels[i*2+j*2*x2+x2]=C


    Next i
    Next j
    'if src then imagedestroy src
    'src=dst

#endif
End Sub

sub ImageEagle overload(byref buffer as FBImage ptr)
dim dest as FBImage ptr
ImageEagle buffer,dest
if buffer then imagedestroy buffer
buffer=dest
end sub

sub ImageEagleMT(byref buffer as FBImage ptr)
dim dest as FBImage ptr
ImageEagle buffer,dest
if buffer then imagedestroy buffer
buffer=dest
end sub
dim shared as any ptr osgl_imageeagle_thread
dim shared as any ptr osgl_imageeagle_ptr
osgl_imageeagle_ptr=@imageeagleMT

sub ImageScale2X overload(byref buffer as FBImage ptr,byref dest as FBImage ptr)
#if __FB_LANG__="fb"

'scale2x
'  A    --\ 1 2
'C P B  --/ 3 4
'  D
'1=P; 2=P; 3=P; 4=P;
'IF C==A AND C!=D AND A!=B => 1=A
'IF A==B AND A!=C AND B!=D => 2=B
'IF B==D AND B!=A AND D!=C => 4=D
'IF D==C AND D!=B AND C!=A => 3=C

    dim as integer x,y,x2,y2,i2,j2,j2x2,jx,pitch1,pitch2,pitch14,pitch24
    dim as uinteger ptr srcpixels,destpixels
    dim as uinteger A,B,C,D,P
    'result = ImageInfo ( [width] [, [height] [, [bypp] [, [pitch] [, [pixdata] [, [imgsize]]]]]] )
    imageinfo buffer,x,y,,pitch1,srcpixels
    pitch14=pitch1/4
    if dest=0 then dest=imagecreate(x*2,y*2,,32)
    imageinfo dest,x2,y2,,pitch2,destpixels
    pitch24=pitch2/4

    for j as integer=0 to y-1
    jx=j*pitch14
    j2=j*2
    j2x2=j2*pitch24
    for i as integer=0 to x-1
    i2=i*2
    P=srcpixels[i+jx]
    destpixels[i2+j2x2]=P
    destpixels[i2+1+j2x2]=P
    destpixels[i2+j2x2+x2]=P
    destpixels[i2+1+j2x2+x2]=P
    next i
    next j

    for j as integer=1 to y-2
    jx=j*pitch14
    j2=j+j
    j2x2=j2*pitch24
    for i as integer=1 to x-2
    i2=i+i
    P=srcpixels[i+jx]
    A=srcpixels[i+(j-1)*pitch14]
    B=srcpixels[i+1+jx]
    C=srcpixels[i-1+jx]
    D=srcpixels[i+(j+1)*pitch14]

    if C=A and C<>D and A<>B then destpixels[i2+j2x2]=A
    if A=B and A<>C and B<>D then destpixels[i2+1+j2x2]=B
    if B=D and B<>A and D<>C then destpixels[i2+1+j2x2+x2]=D
    if D=C and D<>B and C<>A then destpixels[i2+j2x2+x2]=C


    next i
    next j
#endif
end sub

sub ImageScale2X overload(byref buffer as FBImage ptr)
dim dest as FBImage ptr
ImageScale2X buffer,dest
if buffer then imagedestroy buffer
buffer=dest
end sub

sub ImageScale2XMT(byref buffer as FBImage ptr)
dim dest as FBImage ptr
ImageScale2X buffer,dest
if buffer then imagedestroy buffer
buffer=dest
end sub
dim shared as any ptr osgl_imagescale2x_thread
dim shared as any ptr osgl_imagescale2x_ptr
osgl_imagescale2x_ptr=@imagescale2xMT

sub ImageDouble overload(byref buffer as FBImage ptr,byref dest as FBImage ptr)

    dim as integer x,y,x2,y2,i2,j2,j2x2,jx,pitch1,pitch2,pitch14,pitch24
    dim as uinteger ptr srcpixels,destpixels
    dim as uinteger A,B,C,D,P
    'result = ImageInfo ( [width] [, [height] [, [bypp] [, [pitch] [, [pixdata] [, [imgsize]]]]]] )
    imageinfo buffer,x,y,,pitch1,srcpixels
    pitch14=pitch1/4
    if dest=0 then dest=imagecreate(x*2,y*2,,32)
    imageinfo dest,x2,y2,,pitch2,destpixels
    pitch24=pitch2/4

    for j as integer=0 to y-1
    jx=j*pitch14
    j2=j*2
    j2x2=j2*pitch24
    for i as integer=0 to x-1
    i2=i*2
    P=srcpixels[i+jx]
    'line buffer2,(i*2,j*2)-(i*2+1,j*2+1),P,BF
    destpixels[i2+j2x2]=P
    destpixels[i2+1+j2x2]=P
    destpixels[i2+j2x2+x2]=P
    destpixels[i2+1+j2x2+x2]=P
    next i
    next j

end sub

sub ImageDouble overload(byref buffer as FBImage ptr)
dim dest as FBImage ptr
ImageDouble buffer,dest
if buffer then imagedestroy buffer
buffer=dest
end sub

sub ImageDoubleMT(byref buffer as FBImage ptr)
dim dest as FBImage ptr
ImageDouble buffer,dest
if buffer then imagedestroy buffer
buffer=dest
end sub
dim shared as any ptr osgl_imagedouble_thread
dim shared as any ptr osgl_imagedouble_ptr
osgl_imagedouble_ptr=@imagedoubleMT

sub ImageScale(byref buffer as FBImage ptr,byval x as single=1.0,byval y as single=1.0)
    dim as integer origx,origy
    imageinfo buffer,origx,origy
    dim buffer2 as FBImage ptr=imagecreate(x,y,0,32)
    'put buffer2,(0,0),buffer,pset
    rotozoom buffer2,buffer,0,0,0,x,y,0
    'rotozoom 0,texturearray(texturenumber).tmpimage,x1-(xcenter*texturearray(texturenumber).xslicesize)+xoffset,y1-(ycenter*texturearray(texturenumber).yslicesize)+yoffset,360-int(angle),mirror*xscale,flipp*yscale,0
    if buffer then imagedestroy buffer
    buffer=buffer2
end sub

sub imagecopy(byval src as FBImage ptr,byref dst as FBImage ptr)
dim as uinteger x,y
imageinfo src,x,y
printconsole "CACETA",x,y
if dst=0 then dst=imagecreate(x,y,0,32)
put dst,(0,0),src,pset
end sub

sub ImageScale2XandEagle overload(byref buffer as FBImage ptr,byref dest as FBImage ptr)
dim as double mytime1=timer()
dim as uinteger x,y,x2,y2,pitch,pitch4
dim as ubyte a
imageinfo buffer,x,y
dim as colortype ptr pixelse,pixelss,pixels2
if dest=0 then dest=imagecreate(x*2,y*2,0,32)
dim dest2   as FBImage ptr=imagecreate(x*2,y*2,0,32)
dim buffer2 as FBImage ptr=imagecreate(x*2,y*2,0,32)
dim buffere as FBImage ptr=imagecreate(x*2,y*2,0,32)
dim buffers as FBImage ptr=imagecreate(x*2,y*2,0,32)
'dim buffero as FBImage ptr=imagecreate(x*2,y*2,0,32)
'put buffers,(0,0),buffer,pset
'put buffer2,(0,0),buffer,pset
'put dest,(0,0),buffer,pset
ImageDouble buffer,buffer2
imageinfo buffer2,x2,y2,,pitch,pixels2
ImageScale2X buffer,buffers
imageinfo buffers,x2,y2,,pitch,pixelss
ImageEagle buffer,buffere
imageinfo buffere,x2,y2,,pitch,pixelse
pitch4=pitch/4

'put dest2,(0,0),buffere,alpha,255
put dest2,(0,0),buffer2,alpha,255
put dest2,(0,0),buffere,alpha,127
put dest2,(0,0),buffers,alpha,63

put dest,(0,0),dest2,pset

for ii as integer=-1 to 1
for jj as integer=-1 to 1
	a=11
	if abs(ii)=1 and abs(jj)=1 then a=2
	put dest,(ii,jj),dest2,alpha,a
next jj
next ii

if dest2   then imagedestroy dest2  :dest2  =0
if buffers then imagedestroy buffers:buffers=0
if buffer2 then imagedestroy buffer2:buffer2=0
if buffere then imagedestroy buffere:buffere=0
printdebug "Texture: the pixel scaler took me "+str(timer()-mytime1)+" seconds."
end sub


sub ImageScale2XandEagle__ overload(byref buffer as FBImage ptr,byref dest as FBImage ptr)
dim as double mytime1=timer()
dim as uinteger x,y,x2,y2,pitch,pitch4
imageinfo buffer,x,y
dim as colortype ptr pixelse,pixelss,pixels2
if dest=0 then dest=imagecreate(x*2,y*2,0,32)
dim buffer2 as FBImage ptr=imagecreate(x*2,y*2,0,32)
dim buffere as FBImage ptr=imagecreate(x*2,y*2,0,32)
dim buffers as FBImage ptr=imagecreate(x*2,y*2,0,32)
'dim buffero as FBImage ptr=imagecreate(x*2,y*2,0,32)
'put buffers,(0,0),buffer,pset
'put buffer2,(0,0),buffer,pset
'put dest,(0,0),buffer,pset
ImageDouble buffer,buffer2
imageinfo buffer2,x2,y2,,pitch,pixels2
ImageScale2X buffer,buffers
imageinfo buffers,x2,y2,,pitch,pixelss
ImageEagle buffer,buffere
imageinfo buffere,x2,y2,,pitch,pixelse
pitch4=pitch/4

put dest,(0,0),buffere,alpha,255
put dest,(0,0),buffer2,alpha,57
put dest,(0,0),buffers,alpha,57

put dest,(1,0),buffer2,alpha,21
put dest,(1,0),buffers,alpha,21

put dest,(0,1),buffer2,alpha,21
put dest,(0,1),buffers,alpha,21

exit sub
'printconsole "Aaaaaaaaaaaaaaaaaa",pixels2,pixelss,pixelse
'screencontrol 104,1
'put buffero,(0,0),buffere,alpha,192
'put buffero,(0,0),buffers,alpha,192
'if myscreen.alphaprimitives=0 then screencontrol 104,0
dim as uinteger jpitch4,j1pitch4,j2pitch4,ijpitch4,ij1pitch4,i1jpitch4,i2j2pitch4
'dim as ulongint aaa

for j as integer=2 to y2-2
jpitch4=j*pitch4
j1pitch4=(j+1)*pitch4
j2pitch4=(j-1)*pitch4
for i as integer=2 to x2-2
'    pixelse[i+j*x2].r=(pixelse[i+j*x2].r+pixelss[i+1+(j+1)*x2].r)/2
'    pixelse[i+j*x2].g=(pixelse[i+j*x2].g+pixelss[i+1+(j+1)*x2].g)/2
'    pixelse[i+j*x2].b=(pixelse[i+j*x2].b+pixelss[i+1+(j+1)*x2].b)/2
'    pixelse[i+j*x2].a=(pixelse[i+j*x2].a+pixelss[i+1+(j+1)*x2].a)/2

'    pixelse[i+j*x2].r=(pixelse[i+1+j*x2].r+pixelss[i+(j+1)*x2].r+pixels2[i+j*x2].r+pixelss[i+j*x2].r+pixelse[i+j*x2].r)\5
'    pixelse[i+j*x2].g=(pixelse[i+1+j*x2].g+pixelss[i+(j+1)*x2].g+pixels2[i+j*x2].g+pixelss[i+j*x2].g+pixelse[i+j*x2].g)\5
'    pixelse[i+j*x2].b=(pixelse[i+1+j*x2].b+pixelss[i+(j+1)*x2].b+pixels2[i+j*x2].b+pixelss[i+j*x2].b+pixelse[i+j*x2].b)\5
'    pixelse[i+j*x2].a=(pixelse[i+1+j*x2].a+pixelss[i+(j+1)*x2].a+pixels2[i+j*x2].a+pixelss[i+j*x2].a+pixelse[i+j*x2].a)\5

'    pixelse[i+j*x2].r=(pixels2[i+j*x2].r+pixelss[i+j*x2].r+pixelse[i+j*x2].r+pixelse[i+1+j*x2].r+pixelse[i+(j+1)*x2].r)\5
'    pixelse[i+j*x2].g=(pixels2[i+j*x2].g+pixelss[i+j*x2].g+pixelse[i+j*x2].g+pixelse[i+1+j*x2].g+pixelse[i+(j+1)*x2].g)\5
'    pixelse[i+j*x2].b=(pixels2[i+j*x2].b+pixelss[i+j*x2].b+pixelse[i+j*x2].b+pixelse[i+1+j*x2].b+pixelse[i+(j+1)*x2].b)\5
'    pixelse[i+j*x2].a=(pixels2[i+j*x2].a+pixelss[i+j*x2].a+pixelse[i+j*x2].a+pixelse[i+1+j*x2].a+pixelse[i+(j+1)*x2].a)\5

'    pixelse[i+j*x2].r=(pixels2[i+j*x2].r+pixelse[i+1+j*x2].r+pixelss[i+(j+1)*x2].r)/3
'    pixelse[i+j*x2].g=(pixels2[i+j*x2].g+pixelse[i+1+j*x2].g+pixelss[i+(j+1)*x2].g)/3
'    pixelse[i+j*x2].b=(pixels2[i+j*x2].b+pixelse[i+1+j*x2].b+pixelss[i+(j+1)*x2].b)/3
'    pixelse[i+j*x2].a=(pixels2[i+j*x2].a+pixelse[i+1+j*x2].a+pixelss[i+(j+1)*x2].a)/3

'    pixelse[i+j*x2].r=(pixelse[i+j*x2].r+pixelss[i+1+j*x2].r+pixels2[i+(j+1)*x2].r)/3
'    pixelse[i+j*x2].g=(pixelse[i+j*x2].g+pixelss[i+1+j*x2].g+pixels2[i+(j+1)*x2].g)/3
'    pixelse[i+j*x2].b=(pixelse[i+j*x2].b+pixelss[i+1+j*x2].b+pixels2[i+(j+1)*x2].b)/3
'    pixelse[i+j*x2].a=(pixelse[i+j*x2].a+pixelss[i+1+j*x2].a+pixels2[i+(j+1)*x2].a)/3

'    pixelse[i+j*x2].r=(pixelss[i+j*x2].r+pixelse[i+j*x2].r+pixelss[i+1+j*x2].r+pixelse[i+(j-1)*x2].r)\4
'    pixelse[i+j*x2].g=(pixelss[i+j*x2].g+pixelse[i+j*x2].g+pixelss[i+1+j*x2].g+pixelse[i+(j-1)*x2].g)\4
'    pixelse[i+j*x2].b=(pixelss[i+j*x2].b+pixelse[i+j*x2].b+pixelss[i+1+j*x2].b+pixelse[i+(j-1)*x2].b)\4
'    pixelse[i+j*x2].a=(pixelss[i+j*x2].a+pixelse[i+j*x2].a+pixelss[i+1+j*x2].a+pixelse[i+(j-1)*x2].a)\4

    'pixelse[i+j*x2].r=(pixelse[i+j*x2].r+pixelss[i+j*x2].r+(pixelss[i+(j-1)*x2].r+pixelss[i-1+j*x2].r+pixelss[i-1+(j-1)*x2].r)/3)/3
    'pixelse[i+j*x2].g=(pixelse[i+j*x2].g+pixelss[i+j*x2].g+(pixelss[i+(j-1)*x2].g+pixelss[i-1+j*x2].g+pixelss[i-1+(j-1)*x2].g)/3)/3
    'pixelse[i+j*x2].b=(pixelse[i+j*x2].b+pixelss[i+j*x2].b+(pixelss[i+(j-1)*x2].b+pixelss[i-1+j*x2].b+pixelss[i-1+(j-1)*x2].b)/3)/3
    'pixelse[i+j*x2].a=(pixelse[i+j*x2].a+pixelss[i+j*x2].a+(pixelss[i+(j-1)*x2].a+pixelss[i-1+j*x2].a+pixelss[i-1+(j-1)*x2].a)/3)/3


'    pixelse[i+j*x2].r=(pixelss[i+j*x2].r+pixelse[i+j*x2].r+(pixelse[i+(j-1)*x2].r+pixelse[i-1+j*x2].r)/2)/3
'    pixelse[i+j*x2].g=(pixelss[i+j*x2].g+pixelse[i+j*x2].g+(pixelse[i+(j-1)*x2].g+pixelse[i-1+j*x2].g)/2)/3
'    pixelse[i+j*x2].b=(pixelss[i+j*x2].b+pixelse[i+j*x2].b+(pixelse[i+(j-1)*x2].b+pixelse[i-1+j*x2].b)/2)/3
'    pixelse[i+j*x2].a=(pixelss[i+j*x2].a+pixelse[i+j*x2].a+(pixelse[i+(j-1)*x2].a+pixelse[i-1+j*x2].a)/2)/3

    'pixelse[i+j*pitch4].r=(pixelse[i+1+j*pitch4].r+pixelss[i+(j+1)*pitch4].r+pixelss[i+j*pitch4].r+pixelse[i+j*pitch4].r)\5
    'pixelse[i+j*pitch4].g=(pixelse[i+1+j*pitch4].g+pixelss[i+(j+1)*pitch4].g+pixelss[i+j*pitch4].g+pixelse[i+j*pitch4].g)\5
    'pixelse[i+j*pitch4].b=(pixelse[i+1+j*pitch4].b+pixelss[i+(j+1)*pitch4].b+pixelss[i+j*pitch4].b+pixelse[i+j*pitch4].b)\5
    'pixelse[i+j*pitch4].a=(pixelse[i+1+j*pitch4].a+pixelss[i+(j+1)*pitch4].a+pixelss[i+j*pitch4].a+pixelse[i+j*pitch4].a)\5

'    pixelse[i+j*pitch4].r=(2*(pixelse[i+j*pitch4].r+pixelss[i+j*pitch4].r+pixels2[i+j*pitch4].r)+pixelse[i+1+j*pitch4].r+pixelse[i+(j+1)*pitch4].r+pixelss[i-1+j*pitch4].r+pixelss[i+(j-1)*pitch4].r)\10
 '   pixelse[i+j*pitch4].g=(2*(pixelse[i+j*pitch4].g+pixelss[i+j*pitch4].g+pixels2[i+j*pitch4].g)+pixelse[i+1+j*pitch4].g+pixelse[i+(j+1)*pitch4].g+pixelss[i-1+j*pitch4].g+pixelss[i+(j-1)*pitch4].g)\10
  '  pixelse[i+j*pitch4].b=(2*(pixelse[i+j*pitch4].b+pixelss[i+j*pitch4].b+pixels2[i+j*pitch4].b)+pixelse[i+1+j*pitch4].b+pixelse[i+(j+1)*pitch4].b+pixelss[i-1+j*pitch4].b+pixelss[i+(j-1)*pitch4].b)\10
   ' pixelse[i+j*pitch4].a=(2*(pixelse[i+j*pitch4].a+pixelss[i+j*pitch4].a+pixels2[i+j*pitch4].a)+pixelse[i+1+j*pitch4].a+pixelse[i+(j+1)*pitch4].a+pixelss[i-1+j*pitch4].a+pixelss[i+(j-1)*pitch4].a)\10

    'pixelse[i+j*pitch4].colour=(2*(pixelse[i+j*pitch4].colour+pixelss[i+j*pitch4].colour+pixels2[i+j*pitch4].colour)+pixelse[i+1+j*pitch4].colour+pixelse[i+(j+1)*pitch4].colour+pixelss[i-1+j*pitch4].colour+pixelss[i+(j-1)*pitch4].colour)\10

    'pixelse[i+j*pitch4].colour=(pixelse[i+j*pitch4].colour+pixelss[i+j*pitch4].colour+pixels2[i+j*pitch4].colour)/3
    'pixelse[i+j*pitch4].colour=(pixelse[i+j*pitch4].colour+pixelss[i+j*pitch4].colour)/2

    'pixelse[i+j*pitch4].r=(3*(pixelse[i+j*pitch4].r+pixelss[i+j*pitch4].r)+2*pixels2[i+j*pitch4].r+pixelse[i+1+j*pitch4].r+pixelse[i+(j+1)*pitch4].r+pixelss[i+1+(j+1)*pitch4].r)/11
    'pixelse[i+j*pitch4].g=(3*(pixelse[i+j*pitch4].g+pixelss[i+j*pitch4].g)+2*pixels2[i+j*pitch4].g+pixelse[i+1+j*pitch4].g+pixelse[i+(j+1)*pitch4].g+pixelss[i+1+(j+1)*pitch4].g)/11
    'pixelse[i+j*pitch4].b=(3*(pixelse[i+j*pitch4].b+pixelss[i+j*pitch4].b)+2*pixels2[i+j*pitch4].b+pixelse[i+1+j*pitch4].b+pixelse[i+(j+1)*pitch4].b+pixelss[i+1+(j+1)*pitch4].b)/11
    'pixelse[i+j*pitch4].a=(3*(pixelse[i+j*pitch4].a+pixelss[i+j*pitch4].a)+2*pixels2[i+j*pitch4].a+pixelse[i+1+j*pitch4].a+pixelse[i+(j+1)*pitch4].a+pixelss[i+1+(j+1)*pitch4].a)/11

'    pixelse[i+j*pitch4].colour=rgba(	(2*(pixelse[i+j*pitch4].r+pixelss[i+j*pitch4].r+pixels2[i+j*pitch4].r)+pixelse[i+1+j*pitch4].r+pixelse[i+(j+1)*pitch4].r+pixelss[i-1+j*pitch4].r+pixelss[i+(j-1)*pitch4].r)\10,_
'							(2*(pixelse[i+j*pitch4].g+pixelss[i+j*pitch4].g+pixels2[i+j*pitch4].g)+pixelse[i+1+j*pitch4].g+pixelse[i+(j+1)*pitch4].g+pixelss[i-1+j*pitch4].g+pixelss[i+(j-1)*pitch4].g)\10,_
'							(2*(pixelse[i+j*pitch4].b+pixelss[i+j*pitch4].b+pixels2[i+j*pitch4].b)+pixelse[i+1+j*pitch4].b+pixelse[i+(j+1)*pitch4].b+pixelss[i-1+j*pitch4].b+pixelss[i+(j-1)*pitch4].b)\10,_
'							(2*(pixelse[i+j*pitch4].a+pixelss[i+j*pitch4].a+pixels2[i+j*pitch4].a)+pixelse[i+1+j*pitch4].a+pixelse[i+(j+1)*pitch4].a+pixelss[i-1+j*pitch4].a+pixelss[i+(j-1)*pitch4].a)\10)
    ijpitch4=i+jpitch4
    ij1pitch4=i+j1pitch4
    i1jpitch4=i+1+jpitch4
    i2j2pitch4=i-1+j2pitch4
'printconsole "AQUI!"

    pixelse[i+j*pitch4].colour=rgba(	(2*(pixelse[ijpitch4].r+pixelss[ijpitch4].r+pixels2[ijpitch4].r)+pixelse[i1jpitch4].r+pixelse[ij1pitch4].r+pixelse[i2j2pitch4].r)/9,_
							(2*(pixelse[ijpitch4].g+pixelss[ijpitch4].g+pixels2[ijpitch4].g)+pixelse[i1jpitch4].g+pixelse[ij1pitch4].g+pixelse[i2j2pitch4].g)/9,_
							(2*(pixelse[ijpitch4].b+pixelss[ijpitch4].b+pixels2[ijpitch4].b)+pixelse[i1jpitch4].b+pixelse[ij1pitch4].b+pixelse[i2j2pitch4].b)/9,_
							(2*(pixelse[ijpitch4].a+pixelss[ijpitch4].a+pixels2[ijpitch4].a)+pixelse[i1jpitch4].a+pixelse[ij1pitch4].a+pixelse[i2j2pitch4].a)/9)

'aaa=(pixelse[ijpitch4].colour+pixelss[ijpitch4].colour)/2
 '   pixelse[i+j*pitch4].colour=aaa

next i
next j
'if buffer then imagedestroy buffer:buffer=0
if buffers then imagedestroy buffers:buffers=0
if buffer2 then imagedestroy buffer2:buffer2=0
printdebug "Texture: the pixel scaler took me "+str(timer()-mytime1)+" seconds."
end sub

sub ImageScale2XandEagle overload(byref buffer as FBImage ptr)
dim dest as FBImage ptr
ImageScale2XandEagle buffer,dest
if buffer then imagedestroy buffer
buffer=dest
end sub

sub ImageResize(byref buffer as FBImage ptr,byval x as uinteger=1,byval y as uinteger=1)
    dim buffer2 as FBImage ptr=imagecreate(x,y,0,32)
    put buffer2,(0,0),buffer,pset
    if buffer then imagedestroy buffer
    buffer=buffer2
end sub

sub ImageBorderFilter(byref buffer as FBImage ptr)
type ColorTypeb
    r as ubyte
    g as ubyte
    b as ubyte
    a as ubyte
end type

Union ColorUnion
    value As uinteger
    component as colortypeb
End Union

    dim as integer x,y
    dim p1 as colorunion
    dim p2 as colorunion
    dim p3 as colorunion
    dim p4 as colorunion
    dim black as uinteger=rgba(0,0,0,0)
    imageinfo buffer,x,y
    for j as integer=1 to y-2 step 1
    for i as integer=1 to x-2 step 1
        p1.value=point(i,j,buffer)
        p2.value=point(i+1,j,buffer)
        p3.value=point(i,j+1,buffer)
        p4.value=point(i+1,j+1,buffer)
        if p1.value=black then
            if p2.component.a=255 then
            if p3.component.a=255 then
            if p4.component.a=255 then
                p1.component.r=(p2.component.r+p3.component.r+p4.component.r)/3
                p1.component.g=(p2.component.g+p3.component.g+p4.component.g)/3
                p1.component.b=(p2.component.b+p3.component.b+p4.component.b)/3
                p1.component.a=128
                pset buffer,(i,j),p1.value
            end if
            end if
            end if
        end if
        if p2.value=black then
            if p1.component.a=255 then
            if p3.component.a=255 then
            if p4.component.a=255 then
                p2.component.r=(p1.component.r+p3.component.r+p4.component.r)/3
                p2.component.g=(p1.component.g+p3.component.g+p4.component.g)/3
                p2.component.b=(p1.component.b+p3.component.b+p4.component.b)/3
                p2.component.a=128
                pset buffer,(i+1,j),p1.value
            end if
            end if
            end if
        end if
        if p3.value=black then
            if p2.component.a=255 then
            if p1.component.a=255 then
            if p4.component.a=255 then
                p3.component.r=(p2.component.r+p1.component.r+p4.component.r)/3
                p3.component.g=(p2.component.g+p1.component.g+p4.component.g)/3
                p3.component.b=(p2.component.b+p1.component.b+p4.component.b)/3
                p3.component.a=128
                pset buffer,(i,j+1),p3.value
            end if
            end if
            end if
        end if
        if p4.value=black then
            if p2.component.a=255 then
            if p3.component.a=255 then
            if p1.component.a=255 then
                p4.component.r=(p2.component.r+p3.component.r+p1.component.r)/3
                p4.component.g=(p2.component.g+p3.component.g+p1.component.g)/3
                p4.component.b=(p2.component.b+p3.component.b+p1.component.b)/3
                p4.component.a=128
                pset buffer,(i+1,j+1),p4.value
            end if
            end if
            end if
        end if
    next i
    next j
end sub


sub glUploadBGRATexture(byref texture as integer, byval buffer as any ptr, byval mipmap as integer=0, byval filter as integer=1,byval texformat as GLenum=0)
#IFNDEF _osgl_softrender_
#IFNDEF __FB_DOS__

	myscreen.currenttexture=0
	if texformat=0 then texformat=myscreen.textureformat
    dim as integer w, h, pit
    dim pixdata as ubyte ptr
    imageinfo buffer,w,h,,pit,pixdata
    if isPOT(w)=0 or isPOT(h)=0 then
        w=makePOT(w)
        h=makePOT(h)
        imageresize(buffer,w,h)
        imageinfo buffer,w,h,,pit,pixdata
    end if

    glEnable GL_Texture_2D
    if texture<0 then 'create texture
        'printdebug "I'm creating a teture!!! dah!!!"
        glGenTextures 1, @texture
        glBindTexture GL_Texture_2D, texture
        glTexImage2D GL_Texture_2D, 0, texformat, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixdata
        glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_S, GL_CLAMP )
        glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_T, GL_CLAMP )
        if filter then
            glTexParameterf( GL_Texture_2D, GL_Texture_MAG_FILTER, GL_LINEAR )
            glTexParameterf( GL_Texture_2D, GL_Texture_MIN_FILTER, GL_LINEAR )
        else
            glTexParameterf( GL_Texture_2D, GL_Texture_MAG_FILTER, GL_NEAREST )
            glTexParameterf( GL_Texture_2D, GL_Texture_MIN_FILTER, GL_NEAREST )
        end if
		if mipmap then
			glTexEnvi( GL_Texture_ENV, GL_Texture_ENV_MODE, GL_MODULATE )
		end if
    else 'update texture
        glBindTexture GL_Texture_2D, texture
        glTexSubImage2D GL_TEXTURE_2D,0,0,0, w, h, GL_RGBA,GL_UNSIGNED_BYTE, pixdata
    end if


#ENDIF
#endif
end sub

dim shared osgl_fonttexture as integer=0
dim shared osgl_smallfonttexture as integer=0


#macro osgl_inittexture(texturenumber)
texturearray(texturenumber).number=-1
texturearray(texturenumber).xsize=0
texturearray(texturenumber).ysize=0
texturearray(texturenumber).xslices=1
texturearray(texturenumber).yslices=1
texturearray(texturenumber).xslicesize=0
texturearray(texturenumber).yslicesize=0
texturearray(texturenumber).xslicesizefloat=0
texturearray(texturenumber).yslicesizefloat=0
texturearray(texturenumber).lastframe=0
texturearray(texturenumber).flipped=0
texturearray(texturenumber).ispng=0
texturearray(texturenumber).imagedata=0
texturearray(texturenumber).tmpimage=0
texturearray(texturenumber).currentframe=-1
texturearray(texturenumber).currenttext=""
texturearray(texturenumber).scaled=1
#endmacro


sub osgl_deletetexture(byval texturenumber as integer=-1)
'TODO: apagar só a imagem se for software renderer
'-1=apaga todas
if texturenumber=0 then exit sub
if texturenumber<0 then
    for i as integer=1 to maxtexture
        if i<>osgl_fonttexture then
        if i<>osgl_smallfonttexture then
			osgl_deletetexture(i)
		end if
		end if
    next i
    redim texturearray(1 to maxtexture) as texturetype
    myscreen.screencopytexture=0
    exit sub
end if

if texturearray(texturenumber).imagedata then
    if texturearray(texturenumber).ispng then
        png_destroy texturearray(texturenumber).imagedata
    else
        imagedestroy(texturearray(texturenumber).imagedata)
    end if
    texturearray(texturenumber).imagedata=0
    'deallocate texturearray(texturenumber).imagedata
    printdebug "Texture : unloaded "+str(texturenumber)+" imagedata (software)"
end if

if texturearray(texturenumber).tmpimage then
    imagedestroy(texturearray(texturenumber).tmpimage)
    texturearray(texturenumber).tmpimage=0
    'deallocate texturearray(texturenumber).imagedata
    printdebug "Texture : unloaded "+str(texturenumber)+" tmpimage (software)"
end if

#IFNDEF _osgl_softrender_
if myscreen.useopengl then
if texturearray(texturenumber).number>-1 then
    glDeleteTextures (1,@texturearray(texturenumber).number)
    printdebug "Texture : unloaded "+str(texturenumber)
end if
end if
#endif

osgl_inittexture(texturenumber)

end sub

function osgl_string2chr(cstring as string) as string
dim as uinteger txtlength=Len(cstring)
dim as string outs=""
dim as string aa=""
dim as integer j=0
For i as integer=1 to txtlength
    aa=Mid(cstring,i,1): j=Asc(aa)
	if i>1 then outs+="+"
	outs+="chr("+str(j)+")"
Next i
function=outs
end function

Sub StringReplace (subject As String, oldtext As String, newtext As String)
  Dim As Integer n
  If subject <> "" And oldtext <> "" And oldtext <> newtext Then
    n = Instr(subject, oldtext)
    Do While n <> 0
      subject = Left(subject,n-1) & newtext & Right(subject,Len(subject)- n - Len(oldtext)+ 1)
      n = Instr(n + Len(newtext),subject, oldtext)
    Loop
  Endif
End Sub

Sub StringToArray2(Byval instring As String,outarray() As String)
    Dim s As String
    Dim index As Integer
    Redim outarray(0) As String
    For n As Integer=0 To Len(instring)
        s=s+Chr$(instring[n])
        Select Case instring[n]
'case ".",","," ",";",":","?","!","+","-","*","/","$","%","<",">","=",""
 Case 46,44,32,59,58,63,33,43,45,42,47,36,37,60,62,61,0
             index=index+1-Lbound(outarray)
    Redim preserve outarray(Lbound(outarray) To  Ubound(outarray)+1)
    For x As Integer= Ubound(outarray) To Lbound(outarray)+index+1 Step -1
      Swap outarray(x),outarray(x-1)
    Next x
    outarray(Lbound(outarray)+index)=s
            s=""
        End Select
    Next n
End Sub

'pak
dim shared as string pakcurrent
dim shared as string pakindexarray()
dim shared pakindexsize as integer
dim shared paknumberoffiles as integer

function osgl_filetype(byval filename as string) as string
dim as integer filenum=freefile2()
dim a4 as string*4
dim a3 as string*3
dim a2 as string*2
dim answer as string*3
answer="???"
open filename for binary access read as #filenum
printdebug "FILE OPEN: #"+str(filenum)
	get #filenum,1,a4

	select case a4

		case chr(&h89)+"PNG": answer="png"

		case "OggS":answer="ogg"

		case "MS3D":answer="ms3"

		case "RIFF"
			get #filenum,9,a4
			if a4="WAVE" then answer="wav"

		case else
			get #filenum,5,a2
			if a2=chr(&h12,&hAF) or a2=chr(&h11,&hAF) then
				answer="flc"
			else
				get #filenum,1,a2
				if a2="BM" then answer="bmp"
			end if

	end select


close #filenum
printdebug "FILE CLOSED: #"+str(filenum)

function=answer

end function


function osgl_fileexist(filename as string)as integer
if dir(filename)="" then
	printdebug "ERROR! "+ filename+" : file not found!"
	function=0
else
	function=1
end if
end function


sub osgl_loadtexturePNG(byref texturenumber as integer=0, byval filename as string,byval usescaler as uinteger=1,byval keycolor as uinteger=0)
if osgl_fileexist(filename)=0 then printconsole "ERROR : could not load file '"+filename+"'" : exit sub
printdebug filename + " is " + osgl_filetype(filename)
if texturenumber=0 then texturenumber=osgl_freetexture
if texturearray(texturenumber).number>-1 then osgl_deletetexture(texturenumber)
osgl_inittexture(texturenumber)
'if texturearray(texturenumber).number<>0 then glDeleteTextures (1,@texturearray(texturenumber).number)
texturearray(texturenumber).filename=filename
texturearray(texturenumber).imagedata=PNG_Load(filename,PNG_TARGET_FBNEW)
texturearray(texturenumber).ispng=1
ImageInfo texturearray(texturenumber).imagedata,texturearray(texturenumber).xsize,texturearray(texturenumber).ysize
texturearray(texturenumber).scaled=1

if usescaler then
if myscreen.texturescale2x then
if texturearray(texturenumber).xsize*2<=myscreen.maxtexturesize then
if texturearray(texturenumber).ysize*2<=myscreen.maxtexturesize then
	'ImageScale2X(texturearray(texturenumber).imagedata) : texturearray(texturenumber).scaled=0.5
	'ImageEagle(texturearray(texturenumber).imagedata) : texturearray(texturenumber).scaled=0.5
	ImageScale2XandEagle(texturearray(texturenumber).imagedata)
	texturearray(texturenumber).scaled=2
end if
end if
	if texturearray(texturenumber).scaled<>2 then
		printdebug "WARNING : Could not scale texture due to max. texture size!"
	end if
end if
end if

ImageInfo texturearray(texturenumber).imagedata,texturearray(texturenumber).xsize,texturearray(texturenumber).ysize
if keycolor<>rgba(0,0,0,0) then osgl_ChangeColor(texturearray(texturenumber).imagedata,keycolor,rgba(0,0,0,0))
if myscreen.useopengl then
    glUploadTexture(texturearray(texturenumber).number, texturearray(texturenumber).imagedata,,myscreen.useBGRA,myscreen.filter)
    'imagedestroy texturearray(texturenumber).imagedata
    'deallocate texturearray(texturenumber).imagedata
    if texturearray(texturenumber).imagedata then png_destroy texturearray(texturenumber).imagedata : texturearray(texturenumber).imagedata=0
end if
osgl_SetTextureFrames (texturenumber,1,1,1)
end sub

'glTexImage2D(GL_TEXTURE_2D, 0, 4, 128, 128, 0, GL_RGBA, GL_UNSIGNED_BYTE, data)
'glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, texturearray(texture).xsize,texturearray(texture).ysize, 0)

sub osgl_createtexture(byref texturenumber as integer=0, byval x as integer=1, byval y as integer=1)
#IFNDEF _osgl_softrender_
myscreen.currenttexture=0
if texturenumber=0 then texturenumber=osgl_freetexture
if texturearray(texturenumber).number>-1 then osgl_deletetexture(texturenumber)
osgl_inittexture(texturenumber)
if myscreen.useopengl then
	texturearray(texturenumber).xsize=MakePOT(x)
	texturearray(texturenumber).ysize=MakePOT(y)
    glEnable GL_TEXTURE_2D
    glGenTextures 1, @texturearray(texturenumber).number
    glBindTexture GL_TEXTURE_2D, texturearray(texturenumber).number
    glTexImage2D GL_TEXTURE_2D, 0, myscreen.textureformat, texturearray(texturenumber).xsize , texturearray(texturenumber).ysize, 0, GL_RGBA, GL_UNSIGNED_BYTE, null
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP )
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP )
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR )
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR )
end if
texturearray(texturenumber).ispng=0
texturearray(texturenumber).lastframe=1
texturearray(texturenumber).flipped=0
texturearray(texturenumber).xslices=2
texturearray(texturenumber).yslices=1
texturearray(texturenumber).xslicesize=x
texturearray(texturenumber).yslicesize=y
texturearray(texturenumber).xslicesizefloat=x/texturearray(texturenumber).xsize
texturearray(texturenumber).yslicesizefloat=y/texturearray(texturenumber).ysize
#ENDIF
end sub

sub glQuad__ (byval x1 as single=0,byval y1 as single=0,byval x2 as single=1,byval y2 as single=0,byval x3 as single=0,byval y3 as single=1,byval x4 as single=1,byval y4 as single=1,_
			byval tx1 as single=0, byval ty1 as single=0, byval tx2 as single=1, byval ty2 as single=0, byval tx3 as single=0, byval ty3 as single=1, byval tx4 as single=1, byval ty4 as single=1)
#IFNDEF _osgl_softrender_
'glLoadIdentity
'glDisable GL_TEXTURE_2D
dim vertices(1 to 4,1 to 2) as single => {{x1,y1},  {x2,y2},  {x3,y3}, {x4,y4}}
'dim vertices(1 to 4,1 to 2) as single => {{x1,y1},  {x2,y2},  {x3,y3}, {x4,y4}}
'dim normals (1 to 4, 1 to 3) as single => {{0,0,1},  {0,0,1},  {0,0,1},  {0,0,1}}
'dim colors (1 to 4, 1 to 4) as single =>{{1,1,1,.1},  {1,1,0,.1},  {1,0,0,1},  {1,0,1,1}}
dim texcoord (1 to 4, 1 to 2) as single =>{{tx1,ty1},  {tx2,ty2},  {tx3,ty3},  {tx4,ty4}}

 '  glEnableClientState(GL_NORMAL_ARRAY)
'    glEnableClientState(GL_COLOR_ARRAY)
    glEnableClientState(GL_VERTEX_ARRAY)
    glEnableClientState(GL_TEXTURE_COORD_ARRAY)
'    glNormalPointer(GL_FLOAT, 0, @normals(1,1))
    glTexCoordPointer(2, GL_FLOAT,0,@texcoord(1,1))
'    glColorPointer(4, GL_FLOAT, 0, @colors(1,1))
    glVertexPointer(2, GL_FLOAT, 0, @vertices(1,1))
'    glVertexPointer(2, GL_FLOAT, 0, @vertices(1,1))

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)

    glDisableClientState(GL_VERTEX_ARRAY)
 '   glDisableClientState(GL_COLOR_ARRAY)
    glDisableClientState(GL_TEXTURE_COORD_ARRAY)
 '   glDisableClientState(GL_NORMAL_ARRAY)
#ENDIF
end sub


sub glQuad3D (byval x1 as single=0,byval y1 as single=0,byval z1 as single=1,byval x2 as single=1,byval y2 as single=0,byval z2 as single=1,byval x3 as single=0,byval y3 as single=1,byval z3 as single=1,byval x4 as single=1,byval y4 as single=1,byval z4 as single=1,_
			byval tx1 as double=0, byval ty1 as double=0, byval tx2 as double=1, byval ty2 as double=0, byval tx3 as double=0, byval ty3 as double=1, byval tx4 as double=1, byval ty4 as double=1)
#IFNDEF _osgl_softrender_
'glLoadIdentity
'glDisable GL_TEXTURE_2D
dim as GLFLOAT xn,yn,zn
select case as const myscreen.objmode
	case 2:xn=1
	case 3:xn=-1
	case 4:zn=1
	case else:yn=1
end select

dim vertices(1 to 4,1 to 3) as GLFLOAT => {{x1,y1,z1},  {x2,y2,z2},  {x3,y3,z3}, {x4,y4,z4}}
'dim vertices(1 to 4,1 to 2) as single => {{x1,y1},  {x2,y2},  {x3,y3}, {x4,y4}}
dim normals (1 to 4, 1 to 3) as GLFLOAT => {{xn,yn,zn},  {xn,yn,zn},  {xn,yn,zn},  {xn,yn,zn}}
'dim colors (1 to 4, 1 to 4) as single =>{{1,1,1,.1},  {1,1,0,.1},  {1,0,0,1},  {1,0,1,1}}
dim texcoord (1 to 4, 1 to 2) as GLDOUBLE =>{{tx1,ty1},  {tx2,ty2},  {tx3,ty3},  {tx4,ty4}}

'    glEnableClientState(GL_COLOR_ARRAY)
    glEnableClientState(GL_NORMAL_ARRAY)
    glEnableClientState(GL_VERTEX_ARRAY)
    glEnableClientState(GL_TEXTURE_COORD_ARRAY)
'    glColorPointer(4, GL_FLOAT, 0, @colors(1,1))
    glNormalPointer(GL_FLOAT, 0, @normals(1,1))
    'glTexCoordPointer(2, GL_FLOAT,0,@texcoord(1,1))
    glTexCoordPointer(2, GL_DOUBLE,0,@texcoord(1,1))
    glVertexPointer(3, GL_FLOAT, 0, @vertices(1,1))
'    glVertexPointer(2, GL_FLOAT, 0, @vertices(1,1))

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)

 '   glDisableClientState(GL_COLOR_ARRAY)
    glDisableClientState(GL_VERTEX_ARRAY)
    glDisableClientState(GL_TEXTURE_COORD_ARRAY)
   glDisableClientState(GL_NORMAL_ARRAY)
#ENDIF
end sub


'RENDER****************************************************************************************************
sub osgl_Render(    byval x1 as single=0,byval y1 as single=0,byval xcenter as single=0.0,byval ycenter as single=0.0,_
                byval z as single=0,_
                byval texturenumber as integer=0,byval frame as integer=0,_
                byval angle as single=0,_
                byval xscale as single=1,byval yscale as single=1,_
                byval xoffset as single=0,byval yoffset as single=0,_
                byval xstretch as single=1,byval ystretch as single=1,_
                byval mirror as integer=0,byval flipp as integer=0,_
                byval xrep as single=1,byval yrep as single=1,byval xscroll as single=0,byval yscroll as single=0,_
                byval blendmode as integer=0,byval depthtest as integer=0,_
		byval colour as uinteger=rgba(255,255,255,255),byval orientation as integer=0)
                'byval r as ubyte=255,byval g as ubyte=255,byval b as ubyte=255,byval a as ubyte=255)

'if texturenumber>ubound(texturearray) then exit sub
if texturenumber=0 then exit sub

yoffset=-yoffset
y1=-y1
z=-z
angle=-angle
dim as colortype mycolor
mycolor.colour=colour
'depthtest=1 : z=20
'z=50

'xscale=xscale/texturearray(texturenumber).scaled
'yscale=yscale/texturearray(texturenumber).scaled

myscreen.virgin=1
'center
'    -1
'-1    0    1
'    1

'osgl_Render(    x1,y1,xcenter,ycenter,_
    '        z,_
    '        texturenumber,xslices,yslices,frame,_
    '        angle,_
    '        xscale,yscale,xoffset,yoffset,_
    '        xstretch,ystretch,_
    '        mirror,flipp,_
    '        xrep,yrep,xscroll,yscroll,_
    '        blendmode,depthtest,_
    '        r,g,b,a)

'*********SOFTWARE
if myscreen.useopengl=0 then
    if myscreen.frameskipon then
    if myscreen.frameskip=0 then
        exit sub
    end if
    end if
' MultiPut [destination],[xmidpos],[ymidpos],source,[xScale],[yScale],[Trans],[Custom],[Param]
'    MultiPut(,x1-xcenter,y1-ycenter,texturearray(texturenumber).imagedata,xscale,yscale,angle,mirror,flipp,0, @trans) ',1=trans
    osgl_wrap(frame,0,texturearray(texturenumber).lastframe)

    if mirror<>0 then mirror=-1 else mirror=1
    if flipp<>0 then flipp=-1 else flipp=1
    if texturearray(texturenumber).flipped then flipp=-flipp

  if texturearray(texturenumber).xslices>1 then
        textureprecalc.xslice=frame mod texturearray(texturenumber).xslices
	osgl_range(textureprecalc.xslice,0,texturearray(texturenumber).xslices)
        textureprecalc.yslice=frame\texturearray(texturenumber).xslices
        if texturearray(texturenumber).xslicesize=0 then texturearray(texturenumber).xslicesize=texturearray(texturenumber).xsize/texturearray(texturenumber).xslices
        if texturearray(texturenumber).yslicesize=0 then texturearray(texturenumber).yslicesize=texturearray(texturenumber).ysize/texturearray(texturenumber).yslices
        'dim tmpimage as FBImage ptr=imagecreate(texturearray(texturenumber).xslicesize,texturearray(texturenumber).yslicesize)
        if frame<>texturearray(texturenumber).currentframe then
            texturearray(texturenumber).currentframe=frame
            get texturearray(texturenumber).imagedata , ( textureprecalc.xslice*texturearray(texturenumber). xslicesize,textureprecalc.yslice*texturearray(texturenumber).yslicesize ) - ( (textureprecalc.xslice+1)*texturearray(texturenumber).xslicesize-1 , (textureprecalc.yslice+1)*texturearray(texturenumber).yslicesize-1 ) , texturearray(texturenumber).tmpimage
        end if
        if texturearray(texturenumber).tmpimage=0 then exit sub
        'Get [source,] [Step] (x1, y1) - [STEP] (x2, y2), dest]
        'MultiPut(,x1-xcenter+xoffset,y1-ycenter+yoffset,tmpimage,xscale,yscale,angle,mirror,flipp,,@trans2) ',1=trans
        'rotozoom( byref dst as FBImage ptr = 0, byref src as const FBImage ptr, byval positx as integer, byval posity as integer, byref angle as integer, byref zoomx as single, byref zoomy as single, byval transcol as uinteger  = &hffff00ff)
        if mirror=1 then
        if flipp=1 then
        if angle=0 then
        if xscale=0 then
        if yscale=0 then
            put (x1-(xcenter*texturearray(texturenumber).xslicesize)+xoffset+myscreen.x/2,y1-(ycenter*texturearray(texturenumber).yslicesize)+yoffset+myscreen.y/2),texturearray(texturenumber).tmpimage,trans
            exit sub
        end if
        end if
        end if
        end if
        end if
	if mirror=1 then angle=360-angle
        rotozoom 0,texturearray(texturenumber).tmpimage,x1-(xcenter*texturearray(texturenumber).xslicesize)+xoffset+myscreen.x/2,y1-(ycenter*texturearray(texturenumber).yslicesize)+yoffset+myscreen.y/2,int(angle),mirror*xscale,flipp*yscale,0

  else

        if texturearray(texturenumber).imagedata=0 then exit sub
        if mirror=1 then
        if flipp=1 then
        if angle=0 then
        if xscale=0 then
        if yscale=0 then
            put (x1-(xcenter*texturearray(texturenumber).xsize)+xoffset+myscreen.x/2,y1-(ycenter*texturearray(texturenumber).ysize)+yoffset+myscreen.y/2),texturearray(texturenumber).imagedata,trans
            exit sub
        end if
        end if
        end if
        end if
        end if
        rotozoom 0,texturearray(texturenumber).imagedata,x1-(xcenter*texturearray(texturenumber).xsize)+xoffset+myscreen.x/2,y1-(ycenter*texturearray(texturenumber).ysize)+yoffset+myscreen.y/2,360-int(angle),mirror*xscale,flipp*yscale,0
        'MultiPut(,x1-xcenter+xoffset,y1-ycenter+yoffset,texturearray(texturenumber).imagedata,xscale,yscale,angle,mirror,flipp,,@trans2) ',1=trans
  end if
  exit sub
end if
'*********SOFTWARE

'if myscreen.rendermode<>0 then osgl_set2dscreen

'PRECALC

if mirror then mirror=-1 else mirror=1
'abrobro
'if flipp then flipp=-1 else flipp=1
if flipp then flipp=1 else flipp=-1
if texturearray(texturenumber).flipped then flipp=-flipp

dim as double xrotate=0.0, yrotate=0.0, zrotate=1.0

'texture xslices
'if xslices<1 then
    'xslices=texturearray(texturenumber).xslices
    textureprecalc.xslicesize=texturearray(texturenumber).xslicesizefloat
'end if

'if yslices<1 then
    'yslices=texturearray(texturenumber).yslices
    textureprecalc.yslicesize=texturearray(texturenumber).yslicesizefloat
'end if

if textureprecalc.xslicesize<0 then
    textureprecalc.xslicesize=1.0/texturearray(texturenumber).xslices
    textureprecalc.yslicesize=1.0/texturearray(texturenumber).yslices
end if

if texturearray(texturenumber).xslicesize=0 then texturearray(texturenumber).xslicesize=texturearray(texturenumber).xsize/texturearray(texturenumber).xslices
if texturearray(texturenumber).yslicesize=0 then texturearray(texturenumber).yslicesize=texturearray(texturenumber).ysize/texturearray(texturenumber).yslices

if texturearray(texturenumber).lastframe<0 then texturearray(texturenumber).lastframe=0
osgl_wrap(frame,0,texturearray(texturenumber).lastframe)

'if texturearray(texturenumber).xslices>1 then
    textureprecalc.xslice=frame mod texturearray(texturenumber).xslices
    osgl_range(textureprecalc.xslice,0,texturearray(texturenumber).xslices)
    textureprecalc.yslice=frame\texturearray(texturenumber).xslices
'    printconsole "render : ";textureprecalc.xslice,textureprecalc.yslice

'textureprecalc.tx(0)=xscroll+textureprecalc.xslice*textureprecalc.xslicesize
'textureprecalc.ty(0)=yscroll+textureprecalc.yslice*textureprecalc.yslicesize
'textureprecalc.tx(1)=xscroll+xrep*(textureprecalc.xslice+1)*textureprecalc.xslicesize
'textureprecalc.ty(1)=yscroll+textureprecalc.yslice*textureprecalc.yslicesize
'textureprecalc.tx(2)=xscroll+xrep*(textureprecalc.xslice+1)*textureprecalc.xslicesize
'textureprecalc.ty(2)=yscroll+yrep*(textureprecalc.yslice+1)*textureprecalc.yslicesize
'textureprecalc.tx(3)=xscroll+textureprecalc.xslice*textureprecalc.xslicesize
'textureprecalc.ty(3)=yscroll+yrep*(textureprecalc.yslice+1)*textureprecalc.yslicesize

'    printconsole "render : ";textureprecalc.yslice,textureprecalc.yslicesize

textureprecalc.tx(0)=textureprecalc.xslice*textureprecalc.xslicesize
textureprecalc.ty(0)=textureprecalc.yslice*textureprecalc.yslicesize

textureprecalc.tx(1)=textureprecalc.tx(0)+textureprecalc.xslicesize
textureprecalc.ty(1)=textureprecalc.ty(0)

textureprecalc.tx(2)=textureprecalc.tx(1)
textureprecalc.ty(2)=textureprecalc.ty(0)+textureprecalc.yslicesize

textureprecalc.tx(3)=textureprecalc.tx(0)
textureprecalc.ty(3)=textureprecalc.ty(2)


'else

'textureprecalc.tx(0)=xscroll
'textureprecalc.ty(0)=yscroll
'textureprecalc.tx(1)=xrep+xscroll
'textureprecalc.ty(1)=yscroll
'textureprecalc.tx(2)=xrep+xscroll
'textureprecalc.ty(2)=yrep+yscroll
'textureprecalc.tx(3)=xscroll
'textureprecalc.ty(3)=yrep+yscroll

'end if

'polygon
'textureprecalc.sx(0)=-mirror*texturearray(texturenumber).xslicesize/2+xcenter
'textureprecalc.sy(0)=-flipp*texturearray(texturenumber).yslicesize/2+ycenter
'textureprecalc.sx(1)=mirror*texturearray(texturenumber).xslicesize/2+xcenter
'textureprecalc.sy(1)=-flipp*texturearray(texturenumber).yslicesize/2+ycenter
'textureprecalc.sx(2)=mirror*texturearray(texturenumber).xslicesize/2+xcenter
'textureprecalc.sy(2)=flipp*texturearray(texturenumber).yslicesize/2+ycenter
'textureprecalc.sx(3)=-mirror*texturearray(texturenumber).xslicesize/2+xcenter
'textureprecalc.sy(3)=flipp*texturearray(texturenumber).yslicesize/2+ycenter

select case as const orientation

case 2,3:
textureprecalc.sz(0)=(-xcenter-mirror)*texturearray(texturenumber).xslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sy(0)=(-ycenter-flipp)*texturearray(texturenumber).yslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sx(0)=0
textureprecalc.sz(1)=(-xcenter+mirror)*texturearray(texturenumber).xslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sy(1)=(-ycenter-flipp)*texturearray(texturenumber).yslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sx(1)=0
textureprecalc.sz(2)=(-xcenter+mirror)*texturearray(texturenumber).xslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sy(2)=(-ycenter+flipp)*texturearray(texturenumber).yslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sx(2)=0
textureprecalc.sz(3)=(-xcenter-mirror)*texturearray(texturenumber).xslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sy(3)=(-ycenter+flipp)*texturearray(texturenumber).yslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sx(3)=0
swap zrotate, xrotate

case 4:
textureprecalc.sx(0)=(-xcenter-mirror)*texturearray(texturenumber).xslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sz(0)=(-ycenter-flipp)*texturearray(texturenumber).yslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sy(0)=0
textureprecalc.sx(1)=(-xcenter+mirror)*texturearray(texturenumber).xslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sz(1)=(-ycenter-flipp)*texturearray(texturenumber).yslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sy(1)=0
textureprecalc.sx(2)=(-xcenter+mirror)*texturearray(texturenumber).xslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sz(2)=(-ycenter+flipp)*texturearray(texturenumber).yslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sy(2)=0
textureprecalc.sx(3)=(-xcenter-mirror)*texturearray(texturenumber).xslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sz(3)=(-ycenter+flipp)*texturearray(texturenumber).yslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sy(3)=0
swap zrotate, yrotate

case else:
textureprecalc.sx(0)=(-xcenter-mirror)*texturearray(texturenumber).xslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sy(0)=(-ycenter-flipp)*texturearray(texturenumber).yslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sz(0)=0
textureprecalc.sx(1)=(-xcenter+mirror)*texturearray(texturenumber).xslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sy(1)=(-ycenter-flipp)*texturearray(texturenumber).yslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sz(1)=0
textureprecalc.sx(2)=(-xcenter+mirror)*texturearray(texturenumber).xslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sy(2)=(-ycenter+flipp)*texturearray(texturenumber).yslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sz(2)=0
textureprecalc.sx(3)=(-xcenter-mirror)*texturearray(texturenumber).xslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sy(3)=(-ycenter+flipp)*texturearray(texturenumber).yslicesize/(2*texturearray(texturenumber).scaled)
textureprecalc.sz(3)=0
end select

'if a>200 then
'	glAlphaFunc GL_GREATER, 0.5
'else
'	glAlphaFunc GL_GREATER, 0.0
'end if
#IFNDEF _osgl_softrender_
glAlphaFunc GL_GREATER, mycolor.a/450

glPushMatrix

for i as integer=0 to myscreen.stereo3d

'glLoadIdentity

osgl_render_redraw:

  if myscreen.stereo3d and myscreen.drawingtotexture=0 then
	if i=0 then
		'glColor4ub r,0,0,a
		'osgl_set3dcoords
		glColorMask(GL_TRUE,GL_FALSE,GL_FALSE,GL_FALSE)
	else
		'glColor4ub 0,g,b,a/2
		osgl_set3dcoords(1)
		'x1-=.1*z
		glColorMask(GL_FALSE,GL_TRUE,GL_TRUE,GL_FALSE)
	end if
  else
	'osgl_set3dcoords
	'glColor4ub mycolor.r,mycolor.g,mycolor.b,mycolor.a
  end if

glColor4ub mycolor.r,mycolor.g,mycolor.b,mycolor.a
glEnable GL_TEXTURE_2D                   '' Enable 2D Texture Mapping
'glDisable GL_TEXTURE_2D                   '' Disable 2D Texture Mapping
'glBlendFunc GL_DST_COLOR,GL_ZERO  '' Blend Screen Color With Zero (Black)
'glBlendFunc GL_SRC_ALPHA, GL_ONE         '' Select The Type Of Blending

if blendmode<>myscreen.currentblendmode then osgl_SetBlendMode(blendmode)


if depthtest then
	if myscreen.stereo3d=0 or i=1 then
		myscreen.usingdepthbuffer=1
		glEnable GL_DEPTH_TEST
	else
		glDisable GL_DEPTH_TEST
	end if
else
	glDisable GL_DEPTH_TEST
end if


	glTranslatef x1+xoffset,y1+yoffset,z+myscreen.eyez
	'glTranslatef x1,y1,z+myscreen.eyez

'billboard
select case orientation

case 1:	'cone billboard
		glScalef xstretch,ystretch,1.0
		'glrotatef myscreen.zangle-degrees(atn((myscreen.camerazl-myscreen.cameraz)/myscreen.eyez)),0,0,-1
		'glrotatef myscreen.yangle-degrees(atn((myscreen.camerayl-myscreen.cameray)/myscreen.eyez)),0,-1,0
		glrotatef myscreen.cameraya,0,1,0
		'glrotatef myscreen.cameraxa,-1,0,0
		'glrotatef myscreen.cameraxa,1,0,0
'		glrotatef myscreen.zangle,0,0,-1
'		glrotatef myscreen.yangle,0,-1,0
'		glrotatef myscreen.xangle,-1,0,0
		'glrotatef degrees(atn((-myscreen.cameraxl+x1+xoffset)/(z-myscreen.eyez-myscreen.camerazl))),0,-1,0
		'glrotatef degrees(atn((-myscreen.camerayl+y1+yoffset)/(z-myscreen.eyez-myscreen.camerazl))),-1,0,0
		'glrotatef myscreen.yangle,0,-1,0
		'glrotatef myscreen.xangle,-1,0,0
		'degrees(atn((xl-x)/(myscreen.eyez)))
		'glrotatef myscreen.yangle+degrees(atn((-myscreen.cameraxl+x1+xoffset)/(myscreen.eyez+z))),0,-1,0
		'glrotatef myscreen.xangle+degrees(atn((-myscreen.camerayl+y1+yoffset)/(myscreen.eyez+z))),-1,0,0
		'glrotatef degrees(atn((myscreen.cameraxl-myscreen.camerax+x1+xoffset)/(myscreen.eyez-z))/2),0,1,0
		'glrotatef degrees(atn((myscreen.camerayl-myscreen.cameray+y1+yoffset)/(myscreen.eyez-z))/2),-1,0,0
		'glrotatef degrees(atn((myscreen.camerayl-myscreen.cameray+y1+yoffset)/(myscreen.eyez+z))),-1,0,0

case -1:	'spherical billboard

		'glrotatef myscreen.cameraya,0,1,0
		'glrotatef myscreen.cameraxa,-1,0,0

		'glrotatef -degrees(atn((x1+xoffset)/(myscreen.eyez-z))),0,1,0
		'glrotatef -degrees(atn((y1+yoffset)/(myscreen.eyez-z))),-1,0,0
		'glrotatef myscreen.zangle,0,0,-1
		'glrotatef myscreen.yangle,0,-1,0
		'glrotatef myscreen.xangle,-1,0,0

		'void billboardCheatSphericalBegin() {

	'dim as integer i,j

	dim as glfloat modelview(15)
	glGetFloatv(GL_MODELVIEW_MATRIX , @modelview(0))
	for i as integer=0 to 2
		for j as integer=0 to 2
			if i=j then
				modelview(i*4+j) = 1.0
			else
				modelview(i*4+j) = 0.0
			end if
		next j
	next i
	glLoadMatrixf(@modelview(0))
	glScalef xstretch,ystretch,1.0

case else: glScalef xstretch,ystretch,1.0

end select


	glRotatef angle, xrotate, yrotate, zrotate
	glScalef xscale,yscale,1.0


'if texturenumber<>currenttexture then
     '   glBindTexture GL_TEXTURE_2D, texturearray(texturenumber).number      '' Select texture
      '  currenttexture=texturenumber
    'end if
    if myscreen.currenttexture<>texturearray(texturenumber).number then osgl_bindtexture texturearray(texturenumber).number

	if xrep<>1 or xscroll<>0 then
		glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_S, GL_REPEAT )
	else
		glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_S, GL_CLAMP )
	end if
	if yrep<>1 or yscroll<>0 then
		glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_T, GL_REPEAT )
	else
	    glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_T, GL_CLAMP )
	end if

'glTexEnvi(GL_TEXTURE_ENV,GL_RGB_SCALE,0.2)


'    glquad( textureprecalc.sx(0),textureprecalc.sy(0),textureprecalc.sx(3),textureprecalc.sy(3),textureprecalc.sx(1),textureprecalc.sy(1),textureprecalc.sx(2),textureprecalc.sy(2),_
'		textureprecalc.tx(0), textureprecalc.ty(0),textureprecalc.tx(3), textureprecalc.ty(3),textureprecalc.tx(1), textureprecalc.ty(1),textureprecalc.tx(2), textureprecalc.ty(2))

    glquad3d( textureprecalc.sx(0),textureprecalc.sy(0),textureprecalc.sz(0),textureprecalc.sx(3),textureprecalc.sy(3),textureprecalc.sz(3),textureprecalc.sx(1),textureprecalc.sy(1),textureprecalc.sz(1),textureprecalc.sx(2),textureprecalc.sy(2),textureprecalc.sz(2),_
		textureprecalc.tx(0), textureprecalc.ty(0),textureprecalc.tx(3), textureprecalc.ty(3),textureprecalc.tx(1), textureprecalc.ty(1),textureprecalc.tx(2), textureprecalc.ty(2))

'    glBegin GL_TRIANGLE_STRIP
'        glTexCoord2f textureprecalc.tx(0), textureprecalc.ty(0)
'        glVertex3f textureprecalc.sx(0),textureprecalc.sy(0),textureprecalc.sz(0)
'        glTexCoord2f textureprecalc.tx(3), textureprecalc.ty(3)
'        glVertex3f textureprecalc.sx(3),textureprecalc.sy(3),textureprecalc.sz(0)
'        glTexCoord2f textureprecalc.tx(1), textureprecalc.ty(1)
'        glVertex3f textureprecalc.sx(1),textureprecalc.sy(1),textureprecalc.sz(0)
'        glTexCoord2f textureprecalc.tx(2), textureprecalc.ty(2)
'        glVertex3f textureprecalc.sx(2),textureprecalc.sy(2),textureprecalc.sz(0)
'    glEnd

'multi-pass blend effects
if blendmode=99 then osgl_setblendmode(13): blendmode=13: goto osgl_render_redraw

next i

'glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_FALSE)
glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE)
glAlphaFunc GL_GREATER, 0.00
glPopMatrix
#endif

end sub




sub osgl_sprite(    byval x as single,byval y as single,byval z as single=0,_
                byval texturenumber as integer,byval frame as integer=0,byval prio as integer=0,_
                byval angle as single=0,byval xscale as single=1.0,byval yscale as single=1.0,byval xstretch as single=1.0,byval ystretch as single=1.0,_
                byval mirror as integer=0,byval flipp as integer=0,_
                byval xoffset as single=0,byval yoffset as single=0,_
                byval blendmode as integer=1,byval depthtest as integer=0,_
		byval colour as uinteger=rgba(255,255,255,255), byval orientation as integer=-1)

if lastdrawnsprite>=maxsprite then
	printdebug "Sprites : Limit exceeded!"
	exit sub
end if
lastdrawnsprite+=1
if lastdrawnsprite>lastsprite then
    lastsprite=lastdrawnsprite
    redim preserve sprite(1 to lastsprite) as osgl_spritetype
end if

sprite(lastdrawnsprite).exist=1
sprite(lastdrawnsprite).x=x
sprite(lastdrawnsprite).y=y
sprite(lastdrawnsprite).z=z
sprite(lastdrawnsprite).prio=prio
sprite(lastdrawnsprite).texture=texturenumber
sprite(lastdrawnsprite).frame=frame
sprite(lastdrawnsprite).angle=angle
sprite(lastdrawnsprite).xscale=xscale
sprite(lastdrawnsprite).yscale=yscale
sprite(lastdrawnsprite).xstretch=xstretch
sprite(lastdrawnsprite).ystretch=ystretch
sprite(lastdrawnsprite).mirror=mirror
sprite(lastdrawnsprite).flipp=flipp
sprite(lastdrawnsprite).xoffset=xoffset
sprite(lastdrawnsprite).yoffset=yoffset
sprite(lastdrawnsprite).blendmode=blendmode
sprite(lastdrawnsprite).depthtest=depthtest
sprite(lastdrawnsprite).colour=colour
sprite(lastdrawnsprite).orientation=orientation

'sorting helper
if lastdrawnsprite>1 then
        If sprite(lastdrawnsprite-1).prio>sprite(lastdrawnsprite).prio Then Swap sprite(lastdrawnsprite-1), sprite(lastdrawnsprite)
end if

end sub


sub osgl_put(byval x as single=0, byval y as single=0, byval z as single=0, byval texture as integer=0, byval frame as integer=0, byval prio as integer=-99999)
if prio<0 then
' osgl_Render(    byval x1 as single=0,byval y1 as single=0,byval xcenter as single=0.0,byval ycenter as single=0.0,_
'                byval z as single=0,_
'                byval texturenumber as integer=0,byval frame as integer=0,_
'                byval angle as single=0,_
'                byval xscale as single=1,byval yscale as single=1,_
'                byval xoffset as single=0,byval yoffset as single=0,_
'                byval xstretch as single=1,byval ystretch as single=1,_
'                byval mirror as integer=0,byval flipp as integer=0,_
'                byval xrep as single=1,byval yrep as single=1,byval xscroll as single=0,byval yscroll as single=0,_
'                byval blendmode as integer=0,byval depthtest as integer=0,_
'		byval colour as uinteger=rgba(255,255,255,255))
osgl_render(x,y,osgl_putparam(0).xcenter,osgl_putparam(0).ycenter,_
			z,texture,frame,_
			osgl_putparam(0).angle,_
			osgl_putparam(0).xscale,osgl_putparam(0).yscale,_
			osgl_putparam(0).xoffset,osgl_putparam(0).yoffset,_
			osgl_putparam(0).xstretch,osgl_putparam(0).ystretch,_
			osgl_putparam(0).mirror,osgl_putparam(0).flipp,_
			osgl_putparam(0).xrep,osgl_putparam(0).yrep,osgl_putparam(0).xscroll,osgl_putparam(0).yscroll,_
			osgl_putparam(0).blendmode,osgl_putparam(0).depthtest,_
			osgl_putparam(0).colour,osgl_putparam(0).orientation)
else
osgl_sprite(x,y,z,_
		texture,frame,prio,_
		osgl_putparam(0).angle,osgl_putparam(0).xscale,osgl_putparam(0).yscale,osgl_putparam(0).xstretch,osgl_putparam(0).ystretch,_
		osgl_putparam(0).mirror,osgl_putparam(0).flipp,_
		osgl_putparam(0).xoffset,osgl_putparam(0).yoffset,_
		osgl_putparam(0).blendmode,osgl_putparam(0).depthtest,_
		osgl_putparam(0).colour, osgl_putparam(0).orientation)
end if
end sub

sub osgl_put_(byval usesprite as osgl_spritetype)
osgl_sprite(usesprite.x,usesprite.y,usesprite.z,_
		usesprite.texture,usesprite.frame,usesprite.prio,_
		usesprite.angle,usesprite.xscale,usesprite.yscale,usesprite.xstretch,usesprite.ystretch,_
		usesprite.mirror,usesprite.flipp,_
		usesprite.xoffset,usesprite.yoffset,_
		usesprite.blendmode,usesprite.depthtest,_
		rgba(usesprite.r,usesprite.g,usesprite.b,usesprite.a), usesprite.orientation)
end sub

declare sub osgl_texline (byval x1 as single=0,byval y1 as single=0,byval z1 as single=0,byval x2 as single=myscreen.x,byval y2 as single=myscreen.y,byval z2 as single=0,_
					byval texturenumber as integer=0,byval frame as integer=0,_
					byval blendmode as integer=1,_
					byval mirror as integer=0, byval flipp as integer=0)




sub osgl_line (byval x1 as single=0,byval y1 as single=0,byval z1 as single=0,byval x2 as single=myscreen.x,byval y2 as single=myscreen.y,byval z2 as single=0,_
            byval blendmode as integer=0, byval linewidth as single=-1,_
            byval colour as uinteger=rgba(255,255,255,255), byval colour2 as uinteger=rgba(255,0,255,0))

if colour2=rgba(255,0,255,0) then colour2=colour

#IFNDEF _osgl_softrender_
y1=-y1
z1=-z1
y2=-y2
z2=-z2

dim as colortype mycolour
dim as colortype mycolour2
mycolour.colour=colour
mycolour2.colour=colour2

glDisable GL_TEXTURE_2D
glDisable GL_DEPTH_TEST

osgl_SetBlendMode(blendmode)
if linewidth<0 then linewidth=myscreen.ratiox

myscreen.virgin=1

glLineWidth linewidth

osgl_SetBlendMode(blendmode)

    glBegin GL_LINE_LOOP
        glColor4ub mycolour.r,mycolour.g,mycolour.b,mycolour.a
        glVertex3f x1,y1,z1+myscreen.eyez
        glColor4ub mycolour2.r,mycolour2.g,mycolour2.b,mycolour2.a
        glVertex3f x2,y2,z2+myscreen.eyez
    glEnd

glLineWidth 1

glEnable GL_TEXTURE_2D

#endif
end sub



dim shared as any ptr osgl_sortsprites_thread
sub  osgl_sortsprites()
Dim Has_Swapped As Integer=0
Do
  Has_Swapped = 0
  For i as integer= 1 To lastdrawnsprite-1
    If sprite(i).prio>sprite(i+1).prio Then Swap sprite(i), sprite(i+1): Has_Swapped = -1
  Next i
Loop While Has_Swapped
end sub
dim shared as any ptr osgl_sortsprites_ptr
osgl_sortsprites_ptr=@osgl_sortsprites

sub osgl_drawsprites(byval xscene as single=0,byval yscene as single=0)
dim as single sprxscale , spryscale , sprxstretch, sprystretch, sprxoff, spryoff, sprxoff2, spryoff2
dim as integer sprmirror, sprflipp, sprblendmode, sprdepthtest, orientation
dim as ubyte sprr, sprg, sprb, spra
if lastdrawnsprite<1 then exit sub
myscreen.virgin=1
'osgl_sortsprites
'osgl_sortsprites_thread=ThreadCreate(osgl_sortsprites_ptr)
'if osgl_sortsprites_thread then ThreadWait(osgl_sortsprites_thread) else osgl_sortsprites
osgl_sortsprites

for i as integer=1 to lastdrawnsprite
sprxscale = sprite(i).xscale : spryscale = sprite(i).yscale
sprxstretch = sprite(i).xstretch : sprystretch = sprite(i).ystretch
sprmirror = sprite(i).mirror : sprflipp = sprite(i).flipp
sprblendmode = sprite(i).blendmode
sprdepthtest=sprite(i).depthtest
sprr=sprite(i).r:sprg=sprite(i).g:sprb=sprite(i).b:spra=sprite(i).a
sprxoff=sprite(i).xoffset : spryoff=sprite(i).yoffset
'sprxoff=0 : spryoff=0
'sprxoff2=0 : spryoff2=0
'sprxoff2=-4*sprite(i).xoffset/(texturearray(sprite(i).texture).xslicesize/2) : spryoff2=4*sprite(i).yoffset/(texturearray(sprite(i).texture).yslicesize/2)
orientation=sprite(i).orientation
    osgl_Render(    sprite(i).x-xscene,sprite(i).y-yscene,sprxoff2,spryoff2,_
                sprite(i).z,_
                sprite(i).texture,sprite(i).frame,_
                sprite(i).angle,_
                sprxscale,spryscale,sprxoff,spryoff,_
                sprxstretch,sprystretch,_
                sprmirror,sprflipp,_
                1,1,1,1,_
                sprblendmode,sprdepthtest,_
                rgba(sprr,sprg,sprb,spra),orientation)
                'sprr,sprg,sprb,spra)
next i
lastdrawnsprite=0
end sub



'GL_TEXTURE_WRAP_S
'GL_TEXTURE_WRAP_T
'            to either GL_CLAMP or GL_REPEAT.


sub osgl_SetBlendMode(byval blendmode as integer)

'sfactor
 '
'
 '   						Specifies how the red, green, blue, and alpha source blending factors are computed. The following symbolic
  '  						constants are accepted: GL_ZERO, GL_ONE,
   ' 						GL_DST_COLOR, GL_ONE_MINUS_DST_COLOR,
    '						GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,
    '						GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, and
    ' 						GL_SRC_ALPHA_SATURATE. The initial value is GL_ONE. Additionally,
    '						if the GL_ARB_imaging extension is supported, the following constants are accepted:
    '						GL_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR,
    '						GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA.


     '           dfactor


    '						Specifies how the red, green, blue, and alpha destination blending factors are computed. Eight symbolic
    '						constants are accepted: GL_ZERO, GL_ONE,
    '						GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR,
    '						GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,
    '						GL_DST_ALPHA, and GL_ONE_MINUS_DST_ALPHA. The initial value is
    '						GL_ZERO. Additionally, if the GL_ARB_imaging extension is
    '						supported, the following constants are accepted: GL_CONSTANT_COLOR,
    '						GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_ALPHA,
    '						GL_ONE_MINUS_CONSTANT_ALPHA.

myscreen.currentblendmode=blendmode

#IFNDEF _osgl_softrender_
glAlphaFunc GL_GREATER, 0
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
'glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)
select case blendmode

	case 99:
    'one color  (-1 depois 13)
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
    glBlendFunc GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND)

    case -1:
    'negative one color
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
    glBlendFunc GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND)
						'GL_MODULATE,
						'GL_DECAL, GL_BLEND, or GL_REPLACE.

    case 11:
    'fidoofdisjfdso
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
    glBlendFunc GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA

    case 1:
    'normal with transparency
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
    glBlendFunc GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA


    case 2:
    'dark / shadow
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
    glBlendFunc GL_SRC_ALPHA, GL_ZERO

    case 3:
    'glow
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
    glBlendFunc GL_SRC_ALPHA, GL_ONE

    case 4:
    'glow2
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
    glBlendFunc GL_SRC_ALPHA, GL_DST_COLOR

    case 5:
    'paint
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
    glBlendFunc GL_SRC_ALPHA, GL_SRC_COLOR

    case 6:
    'dark paint
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
    glBlendFunc GL_SRC_ALPHA_SATURATE,GL_ONE_MINUS_SRC_ALPHA

    case 7:
    'no alpha no blend
    glDisable GL_BLEND
    glDisable GL_ALPHA_TEST

    case 8:
    '
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
	'glBlendFunc GL_ONE_MINUS_SRC_ALPHA,GL_DST_ALPHA
	'glBlendFunc(GL_SRC_COLOR,GL_DST_COLOR)
	'glBlendFunc(GL_ONE,GL_ONE)
	'glBlendFunc(GL_ONE_MINUS_SRC_COLOR,GL_ONE_MINUS_DST_COLOR) 'negative ghost
	'glBlendFunc(GL_ONE_MINUS_SRC_COLOR,GL_DST_COLOR) 'plastic
	'glBlendFunc(GL_ONE_MINUS_SRC_COLOR,GL_ONE_MINUS_SRC_COLOR)
	'glBlendFunc(GL_ONE_MINUS_SRC_COLOR,GL_SRC_COLOR)
	'glBlendFunc(GL_ONE,GL_ZERO)
    glBlendFunc GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA

    case 9:
    'alpha cut edges
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
    glBlendFunc GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
	glAlphaFunc GL_GREATER, 0.7

	case 10:
	'black
	glEnable GL_BLEND
	glEnable GL_ALPHA_TEST
	glBlendFunc GL_ZERO,GL_ONE_MINUS_SRC_ALPHA

    case 11:
    'constant color TEST
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
    'glBlendFunc GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_ALPHA
	'glAlphaFunc GL_GREATER, 0.7
	'glBlendFunc GL_ONE, GL_CONSTANT_COLOR
	'glBlendFunc GL_CONSTANT_COLOR, GL_CONSTANT_COLOR
	'glBlendFunc(GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR)
	'glBlendFunc GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_SRC_ALPHA
	'glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_ALPHA)
	'glBlendFunc(GL_ONE_MINUS_CONSTANT_COLOR,GL_SRC_ALPHA)
	'glBlendFunc GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_SRC_ALPHA
	'glBlendFunc GL_ZERO,GL_ONE_MINUS_SRC_ALPHA
'    glBlendFunc GL_SRC_ALPHA, GL_ZERO
   'glBlendFunc GL_SRC_ALPHA_SATURATE,GL_ONE_MINUS_SRC_ALPHA
    'glBlendFunc GL_SRC_ALPHA, GL_SRC_COLOR

	'glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)
    'glBlendFunc GL_SRC_ALPHA, GL_ONE
'    glBlendFunc GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_SRC_ALPHA
	'glBlendFunc(GL_CONSTANT_COLOR,GL_SRC_ALPHA)
	'glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE)
	glBlendFunc GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND)
						'GL_MODULATE,
						'GL_DECAL, GL_BLEND, or GL_REPLACE.

    case 12:
    'no outlines for ernest
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
	if myscreen.useconstantcolor then
		glBlendFunc GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_SRC_ALPHA
	else
		glBlendFunc GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
	end if

    case 13:
    'glow3
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
    glBlendFunc GL_ONE,GL_ONE

    case 14:
    'outline
    glEnable GL_BLEND
    glEnable GL_ALPHA_TEST
	if myscreen.useconstantcolor then
		glBlendFunc(GL_CONSTANT_COLOR,GL_SRC_ALPHA)
	else
		glBlendFunc(GL_CONSTANT_COLOR,GL_SRC_ALPHA)
	end if

    case else: '0
    'no blend
    glDisable GL_BLEND
    glEnable GL_ALPHA_TEST


end select
#endif
end sub


'RENDER****************************************************************************************************

sub osgl_quad(    byval x1 as single=0,byval y1 as single=0,_
                byval x3 as single=0,byval y3 as single=0,_
                byval z as single=1,_
                byval texturenumber as integer=0,byval frame as integer=0,_
                byval mirror as integer=0,byval flipp as integer=0,_
                byval xrep as single=1,byval yrep as single=1,byval xscroll as single=0,byval yscroll as single=0,_
                byval blendmode as integer=0,byval depthtest as integer=0,_
		byval colour as uinteger=rgba(255,255,255,255))
                'byval r as ubyte=255,byval g as ubyte=255,byval b as ubyte=255,byval a as ubyte=255)
		dim as colortype mycolor
		mycolor.colour=colour

'depthtest=1 : z=100
'z=50
z=-z
y1=-y1
y3=-y3
                dim x2 as single=-999
		dim y2 as single=-999
                dim x4 as single=-999
		dim y4 as single=-999

myscreen.virgin=1

if x2=-999 then x2=x3
if y2=-999 then y2=y1
if x4=-999 then x4=x1
if y4=-999 then y4=y3
'osgl_quad(    x1,y1,_
'            x3,y3,_
'            z,_
'            texturenumber,frame,_
'            mirror,flipp,_
'            xrep,yrep,xscroll,yscroll,_
'            blendmode,depthtest,_
'            r,g,b,a)

'osgl_quad(    x1,y1,_
'            x3,y3,_
'            z,_
'            texturenumber,frame,_
'            mirror,flipp,_
'            xrep,yrep,xscroll,yscroll,_
'            blendmode,depthtest,_
'            r,g,b,a)

if myscreen.useopengl=0 then
    if myscreen.frameskipon then
    if myscreen.frameskip=0 then
        exit sub
    end if
    end if
' MultiPut [destination],[xmidpos],[ymidpos],source,[xScale],[yScale],[Trans],[Custom],[Param]
'    MultiPut(,x1-xcenter,y1-ycenter,texturearray(texturenumber).imagedata,xscale,yscale,angle,mirror,flipp,0, @trans) ',1=trans
    osgl_wrap(frame,0,texturearray(texturenumber).lastframe)

    'if texturearray(texturenumber).xslices>1 then
    '    textureprecalc.xslice=osgl_range(frame mod texturearray(texturenumber).xslices,0,texturearray(texturenumber).xslices)
    '    textureprecalc.yslice=frame\texturearray(texturenumber).xslices
    '    if texturearray(texturenumber).xslicesize=0 then texturearray(texturenumber).xslicesize=texturearray(texturenumber).xsize/texturearray(texturenumber).xslices
    '    if texturearray(texturenumber).yslicesize=0 then texturearray(texturenumber).yslicesize=texturearray(texturenumber).ysize/texturearray(texturenumber).yslices
    '    if frame<>texturearray(texturenumber).currentframe then
    '        texturearray(texturenumber).currentframe=frame
    '        get texturearray(texturenumber).imagedata , ( textureprecalc.xslice*texturearray(texturenumber). xslicesize,textureprecalc.yslice*texturearray(texturenumber).yslicesize ) - ( (textureprecalc.xslice+1)*texturearray(texturenumber).xslicesize-1 , (textureprecalc.yslice+1)*texturearray(texturenumber).yslicesize-1 ) , texturearray(texturenumber).tmpimage
    '    end if
    '    if texturearray(texturenumber).tmpimage=0 then exit sub
    '    rotozoom 0,texturearray(texturenumber).tmpimage,x1,y1,0,mirror*(x4-x1),flipp*(y4-y1),0
    'else
    dim as single xscale=(x3-x1)/texturearray(texturenumber).xslicesize
    dim as single yscale=(y3-y1)/texturearray(texturenumber).yslicesize
        rotozoom 0,texturearray(texturenumber).imagedata,x1+xscale*texturearray(texturenumber).xslicesize/2+myscreen.x/2,y1+yscale*texturearray(texturenumber).yslicesize/2+myscreen.y/2,0,mirror*xscale,flipp*yscale,0
        'printconsole mirror*(x4-x1)/texturearray(texturenumber).xslicesize,flipp*(y4-y1)/texturearray(texturenumber).yslicesize
        'printconsole (x3-x1)/texturearray(texturenumber).xslicesize,(y3-y1)/texturearray(texturenumber).yslicesize
    'end if
    exit sub
end if

'if myscreen.rendermode<>0 then osgl_set2dscreen

'PRECALC

if mirror then mirror=-1 else mirror=1
if flipp then flipp=-1 else flipp=1
if texturearray(texturenumber).flipped then flipp=-flipp

textureprecalc.xslicesize=texturearray(texturenumber).xslicesizefloat
textureprecalc.yslicesize=texturearray(texturenumber).yslicesizefloat

if textureprecalc.xslicesize<0 then
    textureprecalc.xslicesize=1.0/texturearray(texturenumber).xslices
    textureprecalc.yslicesize=1.0/texturearray(texturenumber).yslices
end if

if texturearray(texturenumber).xslicesize=0 then texturearray(texturenumber).xslicesize=texturearray(texturenumber).xsize/texturearray(texturenumber).xslices
if texturearray(texturenumber).yslicesize=0 then texturearray(texturenumber).yslicesize=texturearray(texturenumber).ysize/texturearray(texturenumber).yslices

if texturearray(texturenumber).lastframe<0 then texturearray(texturenumber).lastframe=0
osgl_wrap(frame,0,texturearray(texturenumber).lastframe)

if texturearray(texturenumber).xslices>1 then
    textureprecalc.xslice=frame mod texturearray(texturenumber).xslices
    osgl_range(textureprecalc.xslice,0,texturearray(texturenumber).xslices)
    textureprecalc.yslice=frame\texturearray(texturenumber).xslices

textureprecalc.tx(0)=textureprecalc.xslice*textureprecalc.xslicesize
textureprecalc.ty(0)=textureprecalc.yslice*textureprecalc.yslicesize

textureprecalc.tx(1)=textureprecalc.tx(0)+textureprecalc.xslicesize
textureprecalc.ty(1)=textureprecalc.ty(0)

textureprecalc.tx(2)=textureprecalc.tx(1)
textureprecalc.ty(2)=textureprecalc.ty(0)+textureprecalc.yslicesize

textureprecalc.tx(3)=textureprecalc.tx(0)
textureprecalc.ty(3)=textureprecalc.ty(2)


else

textureprecalc.tx(0)=xscroll
textureprecalc.ty(0)=yscroll
textureprecalc.tx(1)=xrep+xscroll
textureprecalc.ty(1)=yscroll
textureprecalc.tx(2)=xrep+xscroll
textureprecalc.ty(2)=yrep+yscroll
textureprecalc.tx(3)=xscroll
textureprecalc.ty(3)=yrep+yscroll

end if

'polygon

    'glTranslatef x1+xoffset,y1+yoffset,0
    'glScalef xstretch,ystretch,1.0
    'glRotatef angle,0.0,0.0,1.0
    'glScalef xscale,yscale,1.0
#IFNDEF _osgl_softrender_

glPushMatrix

'glLoadIdentity
for i as integer=0 to myscreen.stereo3d

       if myscreen.stereo3d and myscreen.drawingtotexture=0 then
	if i=0 then
		'glColor4ub r,0,0,a
		'osgl_set3dcoords
		glColorMask(GL_TRUE,GL_FALSE,GL_FALSE,GL_FALSE)
	else
		'glColor4ub 0,g,b,a/2
		osgl_set3dcoords(1)
		'x1-=.1*z
		glColorMask(GL_FALSE,GL_TRUE,GL_TRUE,GL_FALSE)
	end if
  else
	'osgl_set3dcoords
	'glColor4ub r,g,b,a
  end if

glColor4ub mycolor.r,mycolor.g,mycolor.b,mycolor.a

glEnable GL_TEXTURE_2D                   '' Enable 2D Texture Mapping
'glDisable GL_TEXTURE_2D                   '' Disable 2D Texture Mapping
'glBlendFunc GL_DST_COLOR,GL_ZERO  '' Blend Screen Color With Zero (Black)
'glBlendFunc GL_SRC_ALPHA, GL_ONE         '' Select The Type Of Blending

osgl_SetBlendMode(blendmode)

'if texturenumber<>currenttexture then
 '   glBindTexture GL_TEXTURE_2D, texturearray(texturenumber).number      '' Select texture
  '  currenttexture=texturenumber
'end if
    if myscreen.currenttexture<>texturearray(texturenumber).number then osgl_bindtexture texturearray(texturenumber).number

	if xrep<>1 or xscroll<>0 then
		glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_S, GL_REPEAT )
	else
		glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_S, GL_CLAMP )
	end if
	if yrep<>1 or yscroll<>0 then
		glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_T, GL_REPEAT )
	else
	        glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_T, GL_CLAMP )
	end if


if depthtest then
'if 0=0 then
    myscreen.usingdepthbuffer=1
    glEnable GL_DEPTH_TEST
    'glColor4ub r,g,b,a
    'glBegin GL_QUADS
'    glBegin GL_TRIANGLE_STRIP
 '       glTexCoord2f textureprecalc.tx(0), textureprecalc.ty(0)
  '      glVertex3f x1,y1,z
  '      glTexCoord2f textureprecalc.tx(3), textureprecalc.ty(3)
  '      glVertex3f x4,y4,z
  '      glTexCoord2f textureprecalc.tx(1), textureprecalc.ty(1)
  '      glVertex3f x2,y2,z
  '      glTexCoord2f textureprecalc.tx(2), textureprecalc.ty(2)
  '      glVertex3f x3,y3,z
  '  glEnd
else
    glDisable GL_DEPTH_TEST
    'glColor4ub r,g,b,a
    'glquad( x1,y1,x4,y4,x2,y2,x3,y3,_
	'	textureprecalc.tx(0), textureprecalc.ty(0),textureprecalc.tx(3), textureprecalc.ty(3),textureprecalc.tx(1), textureprecalc.ty(1),textureprecalc.tx(2), textureprecalc.ty(2))
end if

gltranslatef 0,0,myscreen.eyez

if i=0 then
	if mirror=-1 then
		swap x1,x3
		swap x2,x4
	end if
	if flipp=-1 then
		swap y1,y3
		swap y2,y4
	end if
end if

glquad3d( x1,y1,z,x4,y4,z,x2,y2,z,x3,y3,z,_
		textureprecalc.tx(0), textureprecalc.ty(0),textureprecalc.tx(3), textureprecalc.ty(3),textureprecalc.tx(1), textureprecalc.ty(1),textureprecalc.tx(2), textureprecalc.ty(2))

next i

	if xrep<>1 or xscroll<>0 then
		glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_S, GL_REPEAT )
	else
		glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_S, GL_CLAMP )
	end if
	if yrep<>1 or yscroll<>0 then
		glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_T, GL_REPEAT )
	else
	        glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_T, GL_CLAMP )
	end if

'glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_FALSE)
glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE)

glPopMatrix
#endif

end sub


sub osgl_3dquad(    byval x1 as single=0,byval y1 as single=0,byval z1 as single=0,_
                byval x2 as single=-999,byval y2 as single=-999,byval z2 as single=0,_
                byval x3 as single=0,byval y3 as single=0,byval z3 as single=0,_
                byval x4 as single=-999,byval y4 as single=-999,byval z4 as single=0,_
                byval texturenumber as integer=0,byval frame as integer=0,_
                byval mirror as integer=0,byval flipp as integer=0,_
                byval xrep as single=1,byval yrep as single=1,byval xscroll as single=0,byval yscroll as single=0,_
                byval blendmode as integer=0,byval depthtest as integer=0,_
                byval colour as uinteger=rgba(255,255,255,255))
                'byval r as ubyte=255,byval g as ubyte=255,byval b as ubyte=255,byval a as ubyte=255)

'depthtest=1 : z=100
'z=50
if ubound(texturearray)<texturenumber or texturenumber=0 then
	printdebug "ERROR : Texture "+str(texturenumber)+" not loaded."
	exit sub
end if

z1=-z1
z2=-z2
z3=-z3
z4=-z4

y1=-y1
y2=-y2
y3=-y3
y4=-y4

dim as colortype mycolor
mycolor.colour=colour

myscreen.virgin=1

'osgl_quad(    x1,y1,_
'            x3,y3,_
'            z,_
'            texturenumber,frame,_
'            mirror,flipp,_
'            xrep,yrep,xscroll,yscroll,_
'            blendmode,depthtest,_
'            r,g,b,a)

'osgl_quad(    x1,y1,_
'            x3,y3,_
'            z,_
'            texturenumber,frame,_
'            mirror,flipp,_
'            xrep,yrep,xscroll,yscroll,_
'            blendmode,depthtest,_
'            r,g,b,a)

if myscreen.useopengl=0 then
    if myscreen.frameskipon then
    if myscreen.frameskip=0 then
        exit sub
    end if
    end if
' MultiPut [destination],[xmidpos],[ymidpos],source,[xScale],[yScale],[Trans],[Custom],[Param]
'    MultiPut(,x1-xcenter,y1-ycenter,texturearray(texturenumber).imagedata,xscale,yscale,angle,mirror,flipp,0, @trans) ',1=trans
    osgl_wrap(frame,0,texturearray(texturenumber).lastframe)

    if mirror<>0 then mirror=-1 else mirror=1
    if flipp<>0 then flipp=1 else flipp=-1
    if texturearray(texturenumber).flipped then flipp=-flipp
    'if texturearray(texturenumber).xslices>1 then
    '    textureprecalc.xslice=osgl_range(frame mod texturearray(texturenumber).xslices,0,texturearray(texturenumber).xslices)
    '    textureprecalc.yslice=frame\texturearray(texturenumber).xslices
    '    if texturearray(texturenumber).xslicesize=0 then texturearray(texturenumber).xslicesize=texturearray(texturenumber).xsize/texturearray(texturenumber).xslices
    '    if texturearray(texturenumber).yslicesize=0 then texturearray(texturenumber).yslicesize=texturearray(texturenumber).ysize/texturearray(texturenumber).yslices
    '    if frame<>texturearray(texturenumber).currentframe then
    '        texturearray(texturenumber).currentframe=frame
    '        get texturearray(texturenumber).imagedata , ( textureprecalc.xslice*texturearray(texturenumber). xslicesize,textureprecalc.yslice*texturearray(texturenumber).yslicesize ) - ( (textureprecalc.xslice+1)*texturearray(texturenumber).xslicesize-1 , (textureprecalc.yslice+1)*texturearray(texturenumber).yslicesize-1 ) , texturearray(texturenumber).tmpimage
    '    end if
    '    if texturearray(texturenumber).tmpimage=0 then exit sub
    '    rotozoom 0,texturearray(texturenumber).tmpimage,x1,y1,0,mirror*(x4-x1),flipp*(y4-y1),0
    'else
    dim as single xscale=(x3-x1)/texturearray(texturenumber).xslicesize
    dim as single yscale=(y3-y1)/texturearray(texturenumber).yslicesize
        rotozoom 0,texturearray(texturenumber).imagedata,x1+xscale*texturearray(texturenumber).xslicesize/2+myscreen.x/2,y1+yscale*texturearray(texturenumber).yslicesize/2+myscreen.y/2,0,mirror*xscale,flipp*yscale,0
        'printconsole mirror*(x4-x1)/texturearray(texturenumber).xslicesize,flipp*(y4-y1)/texturearray(texturenumber).yslicesize
        'printconsole (x3-x1)/texturearray(texturenumber).xslicesize,(y3-y1)/texturearray(texturenumber).yslicesize
    'end if
    exit sub
end if 'software

'if myscreen.rendermode<>1 then osgl_set3dscreen

'PRECALC

if mirror then mirror=-1 else mirror=1
if flipp then flipp=-1 else flipp=1
if texturearray(texturenumber).flipped then flipp=-flipp

textureprecalc.xslicesize=texturearray(texturenumber).xslicesizefloat
textureprecalc.yslicesize=texturearray(texturenumber).yslicesizefloat

if textureprecalc.xslicesize<0 then
    textureprecalc.xslicesize=1.0/texturearray(texturenumber).xslices
    textureprecalc.yslicesize=1.0/texturearray(texturenumber).yslices
end if

if texturearray(texturenumber).xslicesize=0 then texturearray(texturenumber).xslicesize=texturearray(texturenumber).xsize/texturearray(texturenumber).xslices
if texturearray(texturenumber).yslicesize=0 then texturearray(texturenumber).yslicesize=texturearray(texturenumber).ysize/texturearray(texturenumber).yslices

if texturearray(texturenumber).lastframe<0 then texturearray(texturenumber).lastframe=0
osgl_wrap(frame,0,texturearray(texturenumber).lastframe)

if texturearray(texturenumber).xslices>1 then
    textureprecalc.xslice=frame mod texturearray(texturenumber).xslices
    osgl_range(textureprecalc.xslice,0,texturearray(texturenumber).xslices)
    textureprecalc.yslice=frame\texturearray(texturenumber).xslices

textureprecalc.tx(0)=textureprecalc.xslice*textureprecalc.xslicesize
textureprecalc.ty(0)=textureprecalc.yslice*textureprecalc.yslicesize

textureprecalc.tx(1)=textureprecalc.tx(0)+textureprecalc.xslicesize
textureprecalc.ty(1)=textureprecalc.ty(0)

textureprecalc.tx(2)=textureprecalc.tx(1)
textureprecalc.ty(2)=textureprecalc.ty(0)+textureprecalc.yslicesize

textureprecalc.tx(3)=textureprecalc.tx(0)
textureprecalc.ty(3)=textureprecalc.ty(2)


else

textureprecalc.tx(0)=xscroll
textureprecalc.ty(0)=yscroll
textureprecalc.tx(1)=xrep+xscroll
textureprecalc.ty(1)=yscroll
textureprecalc.tx(2)=xrep+xscroll
textureprecalc.ty(2)=yrep+yscroll
textureprecalc.tx(3)=xscroll
textureprecalc.ty(3)=yrep+yscroll

end if

'polygon

    'glTranslatef x1+xoffset,y1+yoffset,0
    'glScalef xstretch,ystretch,1.0
    'glRotatef angle,0.0,0.0,1.0
    'glScalef xscale,yscale,1.0
#IFNDEF _osgl_softrender_

glPushMatrix

for i as integer=0 to myscreen.stereo3d

       if myscreen.stereo3d and myscreen.drawingtotexture=0 then
	if i=0 then
		'glColor4ub r,0,0,a
		'osgl_set3dcoords
		glColorMask(GL_TRUE,GL_FALSE,GL_FALSE,GL_FALSE)
	else
		'glColor4ub 0,g,b,a/2
		osgl_set3dcoords(1)
		'x1-=.1*z
		glColorMask(GL_FALSE,GL_TRUE,GL_TRUE,GL_FALSE)
	end if
  else
	'osgl_set3dcoords
	'glColor4ub r,g,b,a
  end if

glColor4ub mycolor.r, mycolor.g, mycolor.b, mycolor.a


'glLoadIdentity
'osgl_set3dcoords

glEnable GL_TEXTURE_2D                   '' Enable 2D Texture Mapping
'glDisable GL_TEXTURE_2D                   '' Disable 2D Texture Mapping
'glBlendFunc GL_DST_COLOR,GL_ZERO  '' Blend Screen Color With Zero (Black)
'glBlendFunc GL_SRC_ALPHA, GL_ONE         '' Select The Type Of Blending

if myscreen.currentblendmode<>blendmode then osgl_SetBlendMode(blendmode)

'if texturenumber<>currenttexture then
 '   glBindTexture GL_TEXTURE_2D, texturearray(texturenumber).number      '' Select texture
  '  currenttexture=texturenumber
'end if
    if myscreen.currenttexture<>texturearray(texturenumber).number then osgl_bindtexture texturearray(texturenumber).number

if xscroll=0 and xrep=1 then
    glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_S, GL_CLAMP )
else
	glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_S, GL_REPEAT )
end if

if yscroll=0 and yrep=1 then
    glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_T, GL_CLAMP )
else
    glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_T, GL_REPEAT )
end if


if depthtest then
    myscreen.usingdepthbuffer=1
    glEnable GL_DEPTH_TEST
else
    glDisable GL_DEPTH_TEST
end if

gltranslatef 0,0,myscreen.eyez

'osgl_popup str(mirror),str(mirror)


if i=0 then
if mirror=-1 then
	swap textureprecalc.tx(0),textureprecalc.tx(1)
	swap textureprecalc.tx(2),textureprecalc.tx(3)
end if

if flipp=-1 then
	swap textureprecalc.ty(0),textureprecalc.ty(2)
	swap textureprecalc.ty(1),textureprecalc.ty(3)
end if
end if

'glColor4ub r,g,b,a
glquad3d( x1,y1,z1,x4,y4,z4,x2,y2,z2,x3,y3,z3,_
		textureprecalc.tx(0), textureprecalc.ty(0),textureprecalc.tx(3), textureprecalc.ty(3),textureprecalc.tx(1), textureprecalc.ty(1),textureprecalc.tx(2), textureprecalc.ty(2))

'osgl_print -100,-100,0,str(mirror)
next i

'glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_FALSE)
glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE)

glPopMatrix
#endif

end sub


sub osgl_CaptureScreenAsTexture(byref texture as integer=0, byval usefrontbuffer as integer=1)
#IFNDEF _osgl_softrender_
glEnable GL_TEXTURE_2D
myscreen.currenttexture=0

if texture=0 then texture=osgl_freetexture
osgl_createtexture(texture,myscreen.realx,myscreen.realy - myscreen.blackborders*myscreen.realx*0.125)
osgl_bindtexture texturearray(texture).number
dim as integer tmpborder=myscreen.blackborders*myscreen.realx*0.0625, tmpx=texturearray(texture).xsize, tmpy=texturearray(texture).ysize

if myscreen.usefrontbuffer=0 then usefrontbuffer=0

if usefrontbuffer then
	glReadBuffer GL_FRONT
else
	flip
end if

'glCopyTexImage2D(GLenum  target,  GLint  level,  GLenum  internalformat,  GLint  x,  GLint  y,  GLsizei  width,  GLsizei  height,  GLint  border);

glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, tmpborder, tmpx, tmpy, 0)

'glCopyTexSubImage2D é muito lento em algumas máquinas que testei (AMD Catalyst = mais provável culpado)
'glCopyTexSubImage2D(GLenum  target,  GLint  level,  GLint  xoffset,  GLint  yoffset,  GLint  x,  GLint  y,  GLsizei  width,  GLsizei  height);
'glCopyTexSubImage2D(GL_TEXTURE_2D, 0,  0, 0,  0, tmpborder,  tmpx, tmpy)

if usefrontbuffer then
	glReadBuffer GL_BACK
else
	flip
end if

texturearray(texture).flipped=0

#ENDIF
end sub



sub osgl_RestoreScreenFromTexture(byref texture as integer=0)

			myscreen.currenttexture=0

            osgl_quad(    -myscreen.x/2+myscreen.xcutpixels,myscreen.y/2,_
            myscreen.x/2-myscreen.xcutpixels,-myscreen.y/2,_
            0,_
            texture,0,_
            0,0,_     'mirror,flip
            1,1,0,0,_   '        xrep,yrep,xscroll,yscroll,_
            7,0,_       '        blendmode,depthtest,_
            rgba(255,255,255,255))    '        r,g,b,a)

end sub

sub osgl_storeframebuffer(byval usefrontbuffer as integer=0)
#IFNDEF _osgl_softrender_
if myscreen.screencopytexture=0 then osgl_createtexture(myscreen.screencopytexture,myscreen.realx,myscreen.realy)
osgl_CaptureScreenAsTexture(myscreen.screencopytexture,usefrontbuffer)
#ENDIF
end sub

sub osgl_restoreframebuffer
osgl_suspendcamera
osgl_RestoreScreenFromTexture(myscreen.screencopytexture)
osgl_restorecamera
end sub


sub osgl_drawtotexture_begin(byval saveframebuffer as integer=1)
#IFNDEF _osgl_softrender_
'glviewport(0,0,texturearray(texture).xsize,texturearray(texture).ysize)
'glFlush
if saveframebuffer then osgl_storeframebuffer
osgl_suspendcamera
myscreen.drawingtotexture=1
glviewport(0,0,myscreen.x,myscreen.y)
'glviewport(myscreen.realx/2-texturearray(texture).xsize/2,myscreen.realy/2-texturearray(texture).ysize/2,myscreen.realx/2+texturearray(texture).xsize/2,myscreen.realy/2+texturearray(texture).ysize/2)
    'glMatrixMode GL_PROJECTION                 '' Select The Projection Matrix
   'glLoadIdentity                             '' Reset The Projection Matrix
    'gluPerspective myscreen.fovy, myscreen.x/myscreen.y, .001, 10000   '' Calculate The Aspect Ratio Of The Window
    'glMatrixMode GL_MODELVIEW                  '' Select The Modelview Matrix
    'glLoadIdentity                             '' Reset The Projection Matrix
    	'glTranslatef(0.0, 0.0, -myscreen.y*myscreen.tanfovy) 'cria o sistema de coordenadas 3d=2d
    	'glTranslatef(myscreen.x/2, 0.0, 0.0) 'cria o sistema de coordenadas 3d=2d
    	'glTranslatef(0.0, myscreen.y/2, 0.0) 'cria o sistema de coordenadas 3d=2d
    	'glTranslatef(0.0, 0.0, -texturearray(texture).ysize*myscreen.tanfovy) 'cria o sistema de coordenadas 3d=2d
	'glScalef( 1, -1, -1 ) 'inverte o eixo y 3d=2d

osgl_cls(0,0,0,255)
#ENDIF
end sub

'void RenderToTexture()							// Renders To A Texture
'{
'	glViewport(0,0,128,128);					// Set Our Viewport (Match Texture Size)
'
'	ProcessHelix();							// Render The Helix
'
'	glBindTexture(GL_TEXTURE_2D,BlurTexture);			// Bind To The Blur Texture
'
'	// Copy Our ViewPort To The Blur Texture (From 0,0 To 128,128... No Border)
'	glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 0, 0, 128, 128, 0);
'
'	glClearColor(0.0f, 0.0f, 0.5f, 0.5);				// Set The Clear Color To Medium Blue
'	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);		// Clear The Screen And Depth Buffer
'
'	glViewport(0 , 0,640 ,480);					// Set Viewport (0,0 to 640x480)
'}

sub osgl_drawtotexture_end(byval texture as integer=0,byval saveframebuffer as integer=1)
#IFNDEF _osgl_softrender_
if myscreen.currenttexture<>texturearray(texture).number then osgl_bindtexture texturearray(texture).number
'glReadBuffer GL_BACK
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, myscreen.x/2-texturearray(texture).xsize/2, myscreen.y/2-texturearray(texture).ysize/2, texturearray(texture).xsize,texturearray(texture).ysize, 0)
'glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 0, 0, texturearray(texture).xsize,texturearray(texture).ysize, 0)
'glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, -texturearray(texture).xsize/2, -texturearray(texture).ysize/2, texturearray(texture).xsize,texturearray(texture).ysize, 0)
'osgl_cls (0,0,0,0)
myscreen.drawingtotexture=0
'glViewport 0, 0, myscreen.realx, myscreen.realy
glviewport 0, myscreen.blackborders*myscreen.realx*0.0625,myscreen.realx,myscreen.realy - myscreen.blackborders*myscreen.realx*0.125
if saveframebuffer then osgl_restoreframebuffer
osgl_restorecamera
#ENDIF
end sub



sub osgl_text2(byref texturenumber as integer,byval x1 as single=0,byval y1 as single=0,byval xscale as single=1.0,byval yscale as single=1.0,byval text as string,byval textlength as uinteger=48,byval textlines as uinteger=1,byval blendmode as uinteger=1,byval r as ubyte=255,byval g as ubyte=255,byval b as ubyte=255,byval a as ubyte=255)
if texturenumber=0 then texturenumber=osgl_freetexture

'osgl_text(texturenumber,x1,y1,x2,y2,text,textcolor,fontsize)


if myscreen.useopengl=0 then
'if xscale=1 then
'if yscale=1 then
dim as string parsetext
parsetext=StringFromList(text,1,chr(10))
for ii as integer=1 to textlines
    draw string (x1,y1+(ii-1)*16),parsetext,rgba(r,g,b,a),,PSET
    parsetext=StringFromList(text,ii+1,chr(10))
    if parsetext="" then exit for
next ii
'end if
'end if
end if


dim as single x2=x1+xscale*makePOT(8*textlength)
dim as single y2=y1+yscale*makePOT(16*textlines)

if text<>texturearray(texturenumber).currenttext then
    osgl_texturetext(texturenumber,textlength,textlines,text,rgba(255,255,255,255),0,2)
    texturearray(texturenumber).currenttext=text
end if
osgl_quad(    x1,y1,_
            x2,y2,_
            0,_
            texturenumber,0,_
            0,0,_
            1,1,0,0,_
            blendmode,0,_
            rgba(r,g,b,a))
end sub

sub osgl_texline (byval x1 as single=0,byval y1 as single=0,byval z1 as single=0,byval x2 as single=myscreen.x,byval y2 as single=myscreen.y,byval z2 as single=0,_
					byval texturenumber as integer=0,byval frame as integer=0,_
					byval blendmode as integer=1,_
					byval mirror as integer=0, byval flipp as integer=0)

dim as double l=sqr((x1-x2)^2+(y1-y2)^2+(z1-z2)^2)
dim as double w=texturearray(texturenumber).xslicesize

dim as double ysc=l/(texturearray(texturenumber).yslicesize+w)
'printconsole l
'printconsole ysc
'end

dim as double n1 = sqr(x1*x1+y1*y1)
dim as double n2 = sqr(x2*x2+y2*y2)
dim as double a = acos((x1*x2+y1*y2)/(n1*n2))*180/PI
'dim as double xa=atn((x2-x1)/(y2-y1))
'dim as double ya=0
'dim as double za=atn((z2-z1)/(y2-y1))

'dim as single xr=atan2(y2 - y1, x2 - x1)
'dim as single zr=atan2(y2 - y1, z2 - z1)


' osgl_3dquad(    byval x1 as single=0,byval y1 as single=0,byval z1 as single=0,_
'                byval x2 as single=-999,byval y2 as single=-999,byval z2 as single=0,_
'                byval x3 as single=0,byval y3 as single=0,byval z3 as single=0,_
'                byval x4 as single=-999,byval y4 as single=-999,byval z4 as single=0,_
'                byval texturenumber as integer=0,byval frame as integer=0,_
'                byval mirror as integer=0,byval flipp as integer=0,_
'                byval xrep as single=1,byval yrep as single=1,byval xscroll as single=0,byval yscroll as single=0,_
'                byval blendmode as integer=0,byval depthtest as integer=0,_
'                byval colour as uinteger=rgba(255,255,255,255))
'osgl_3dquad(x1-w*xr,y1-w/zr,z1,_
'			x2+w*xr,y1-w/zr,z1,_
'			x2+w*xr,y2+w/zr,z2,_
'			x1-w*xr,y2+w/zr,z2,_
'			texturenumber, frame,_
'			mirror, flipp,_
'			blendmode)

osgl_render(    (x1+x2)/2,(y1+y2)/2,0,0,_ 'prio
            (z1+z2)/2,_
            texturenumber,frame,_ 'texture,frame
            -a,1.0,1.0,0,0,_
            1,1,_
            mirror,0,_ 'mirror,flipp
            0,0,0,0,_ 'offset
            12,0,_ 'blendmode
            rgba(255,255,255,255),1)


end sub


sub osgl_box(    byval x1 as single=-myscreen.x/2,byval y1 as single=-myscreen.y/2,byval x2 as single=myscreen.x/2,byval y2 as single=myscreen.y/2,_
            byval blendmode as integer=0,_
            byval r1 as ubyte=0,byval g1 as ubyte=0,byval b1 as ubyte=0,byval a1 as ubyte=255,_
            byval r2 as ubyte=0,byval g2 as ubyte=0,byval b2 as ubyte=0,byval a2 as ubyte=255,_
            byval r3 as ubyte=0,byval g3 as ubyte=0,byval b3 as ubyte=0,byval a3 as ubyte=255,_
            byval r4 as ubyte=0,byval g4 as ubyte=0,byval b4 as ubyte=0,byval a4 as ubyte=255)

y1=-y1
y2=-y2

dim vertices(1 to 4,1 to 3) as single => {{x1,y1,myscreen.eyez},  {x2,y1,myscreen.eyez},  {x1,y2,myscreen.eyez}, {x2,y2,myscreen.eyez}}
dim colors (1 to 4, 1 to 4) as ubyte =>{{r1,g1,b1,a1},  {r2,g2,b2,a2},  {r3,g3,b3,a3},  {r4,g4,b4,a4}}

myscreen.virgin=1

if myscreen.useopengl=0 then
    line (x1,y1)-(x2,y1+(y2-y1)/2),rgba(r1,g1,b1,a1),bf
    line (x1,y1+(y2-y1)/2)-(x2,y2),rgba(r4,g4,b4,a4),bf
    exit sub
end if

#IFNDEF _osgl_softrender_

'glPushMatrix
glDisable GL_TEXTURE_2D
glDisable GL_DEPTH_TEST

osgl_SetBlendMode(blendmode)

    glEnableClientState(GL_COLOR_ARRAY)
    glEnableClientState(GL_VERTEX_ARRAY)
    glVertexPointer(3, GL_FLOAT, 0, @vertices(1,1))
    glColorPointer(4, GL_UNSIGNED_BYTE, 0, @colors(1,1))
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)
    glDisableClientState(GL_VERTEX_ARRAY)
    glDisableClientState(GL_COLOR_ARRAY)

#endif
end sub



sub osgl_cls(byval r as ubyte=0,byval g as ubyte=0,byval b as ubyte=0,byval a as ubyte=255)
'osgl_box
'exit sub
'limpa tela
#IFNDEF _osgl_softrender_
glClearColor r/255,g/255,b/255,a/255
glClearDepth 1.0
#endif
if myscreen.useopengl then
    #IFNDEF _osgl_softrender_
    glClear  GL_COLOR_BUFFER_BIT OR GL_DEPTH_BUFFER_BIT
    #endif
else
	cls rgba(r,g,b,a)
end if
#IFNDEF _osgl_softrender_
glClearColor 0,0,0,0
#endif
end sub

sub osgl_fakefog(byval y1 as integer=-9999,byval y2 as integer=-9999,byval upintensity as single=1.0,byval downintensity as single=0.0,byval blendmode as integer=1,byval colour as uinteger)
'sub osgl_box(    byval x1 as single=0,byval y1 as single=0,byval x2 as single=myscreen.x,byval y2 as single=myscreen.y,_
'            byval blendmode as integer=0,_
'            byval r1 as ubyte=255,byval g1 as ubyte=255,byval b1 as ubyte=255,byval a1 as ubyte=255,_
'            byval r2 as ubyte=255,byval g2 as ubyte=255,byval b2 as ubyte=255,byval a2 as ubyte=255,_
'            byval r3 as ubyte=255,byval g3 as ubyte=255,byval b3 as ubyte=255,byval a3 as ubyte=255,_
'            byval r4 as ubyte=255,byval g4 as ubyte=255,byval b4 as ubyte=255,byval a4 as ubyte=255)
if y1=-9999 then y1=-myscreen.y
if y2=-9999 then y2=myscreen.y
dim as colortype mycolor
mycolor.colour=colour

osgl_suspendcamera
osgl_box(-myscreen.x,y1,myscreen.x,y2,blendmode,_
		mycolor.r*upintensity,mycolor.g*upintensity,mycolor.b*upintensity,mycolor.a*upintensity,_
		mycolor.r*upintensity,mycolor.g*upintensity,mycolor.b*upintensity,mycolor.a*upintensity,_
		mycolor.r*downintensity,mycolor.g*downintensity,mycolor.b*downintensity,mycolor.a*downintensity,_
		mycolor.r*downintensity,mycolor.g*downintensity,mycolor.b*downintensity,mycolor.a*downintensity)
osgl_restorecamera
end sub

sub osgl_energybar(    byval x1 as single=0,byval y1 as single=0,byval x2 as single=myscreen.x,byval y2 as single=myscreen.y,_
                    byval energy as double=1.0,byval flipp as integer=0,_
                    byval rout as ubyte=255,byval gout as ubyte=255,byval bout as ubyte=255,byval aout as ubyte=255,_
                    byval rbak as ubyte=255,byval gbak as ubyte=255,byval bbak as ubyte=255,byval abak as ubyte=255,_
                    byval rbar as ubyte=255,byval gbar as ubyte=255,byval bbar as ubyte=255,byval abar as ubyte=255)

y1=-y1
y2=-y2

if energy<0 then
    energy=0
else
    if energy>1.0 then energy=1.0
end if

dim xbar as double
if flipp=0 then
    xbar=x1+energy*(x2-x1)
else
    xbar=x2-energy*(x2-x1)
end if

if myscreen.useopengl=0 then
    line (x1,y1)-(x2,y2),rgba(rout,gout,bout,aout),bf 'atencao : rgba usa bytes, e não floats!
    if energy<1.0 then line (x1+2,y1+2)-(x2-2,y2-2),rgba(rbak,gbak,bbak,abak),bf 'atencao : rgba usa bytes, e não floats!
    if energy>0.0 then
        if flipp=0 then
            line (x1+2,y1+2)-(xbar+2,y2-2),rgba(rbar,gbar,bbar,abar),bf 'atencao : rgba usa bytes, e não floats!
        else
            line (xbar+2,y1+2)-(x2-2,y2-2),rgba(rbar,gbar,bbar,abar),bf 'atencao : rgba usa bytes, e não floats!
        end if
    end if
    exit sub
end if

#IFNDEF _osgl_softrender_

'glPushMatrix
glDisable GL_TEXTURE_2D                   '' Disable 2D Texture Mapping

#endif

osgl_SetBlendMode(1)

#IFNDEF _osgl_softrender_
if flipp=0 then
    'bak
    'if 1=0 then
    if energy<1.0 then
    'glBegin GL_QUADS
    glBegin GL_TRIANGLE_STRIP
        glColor4ub rbak,gbak,bbak,abak-0.1
        glVertex3f x2,y2, myscreen.eyez
          glVertex3f xbar,y2, myscreen.eyez
        glColor4ub rbak*0.5,gbak*0.5,bbak*0.5,abak+0.2
        glVertex3f x2,y1, myscreen.eyez
        glVertex3f xbar,y1, myscreen.eyez
    glEnd
    end if

    'bar
    'if 1=0 then
    if energy>0.0 then
        'glBegin GL_QUADS
        glBegin GL_TRIANGLE_STRIP
            glColor4ub rbar,gbar,bbar,abar
            glVertex3f x1,y1, myscreen.eyez
            glVertex3f xbar,y1, myscreen.eyez
            glColor4ub rbar*0.5,gbar*0.5,bbar*0.5,abar
            glVertex3f x1,y2, myscreen.eyez
            glVertex3f xbar,y2, myscreen.eyez
        glEnd
    end if
else
    'bak
    'if 1=0 then
    if energy<1.0 then
    'glBegin GL_QUADS
    glBegin GL_TRIANGLE_STRIP
        glColor4ub rbak,gbak,bbak,abak-0.1
        glVertex3f x1+1,y2+1, myscreen.eyez
        glVertex3f xbar,y2+1, myscreen.eyez
        glColor4ub rbak*0.5,gbak*0.5,bbak*0.5,abak+0.2
        glVertex3f x1+1,y1-1, myscreen.eyez
        glVertex3f xbar,y1-1, myscreen.eyez
    glEnd
    end if

    'bar
    'if 1=0 then
    if energy>0.0 then
    'glBegin GL_QUADS
    glBegin GL_TRIANGLE_STRIP
        glColor4ub rbar,gbar,bbar,abar
          glVertex3f xbar,y2, myscreen.eyez
        glVertex3f x2,y2, myscreen.eyez
        glColor4ub rbar*0.5,gbar*0.5,bbar*0.5,abar
        glVertex3f xbar,y1, myscreen.eyez
        glVertex3f x2,y1, myscreen.eyez
    glEnd
    end if
end if

    'outline
    glLineWidth 2
    glBegin GL_LINE_LOOP
        glColor4ub rout,gout,bout,aout
        glVertex3f x1,y1, myscreen.eyez
        glVertex3f x2,y1, myscreen.eyez
        glColor4ub rout*0.5,gout*0.5,bout*0.5,aout
        glVertex3f x2,y2, myscreen.eyez
          glVertex3f x1,y2, myscreen.eyez
    glEnd
    glLineWidth 1

#endif
end sub



sub osgl_clearparticles()
for i As Integer=lastparticle to 0 step -1
    particle(i).exist=0
next i
lastparticle=-1
end sub

'RENDER****************************************************************************************************

sub osgl_particle(      byval x as single =0, byval y as single =0,byval z as single =1,_
                        byval texturenumber as integer =0,_
                        byval xscale as single =1,byval yscale as single =1,byval dxscale as single =0,byval dyscale as single =0,_
                        byval firstframe as integer =0,byval lastframe as integer =0,byval duration as integer,_
                        byval dx as single =0,byval dy as single =0,byval ax as single =0,byval ay as single =0,byval ybounce as integer=-9999,_
                        byval angle as single =0,byval dangle as single =0,_
						byval mirror as integer=0,byval flipp as integer=0,_
                        byval blendmode as integer =1,_
                        byval r as ubyte=255,byval g as ubyte=255,byval b as ubyte=255,byval a as ubyte=255,byval dalpha as single =0,byval text as string="")


'osgl_particle(    x, y, z,_
'            texturenumber, xslices, yslices,_
'            xscale,yscale,dxscale,dyscale,_
'            firstframe, lastframe,duration,_
'            dx, dy, ax, ay,_
'            angle, dangle,_
'            blendmode,_
'            r, g, b, a, dalpha)

if lastparticle>maxparticle-1 then
    'exit sub
    lastparticle=maxparticle
    myparticle=-1
    for j as integer=0 to lastparticle
        'printdebug j
        if particle(j).exist=0 then
            myparticle=j
            'printdebug "Particles : using "+str(j)
            exit for
        end if
    next j
    if myparticle=-1 then
        printdebug "Particles : limit exceeded!"
        exit sub
    end if
else
    lastparticle+=1
    myparticle=lastparticle
end if


particle(myparticle).exist=1
particle(myparticle).x=x
particle(myparticle).y=y
particle(myparticle).z=z
particle(myparticle).mirror=mirror
particle(myparticle).flipp=flipp
particle(myparticle).texture=texturenumber
'particle(myparticle).xslices=xslices
'particle(myparticle).yslices=yslices
particle(myparticle).xscale=xscale
particle(myparticle).yscale=yscale
particle(myparticle).dxscale=dxscale
particle(myparticle).dyscale=dyscale
particle(myparticle).firstframe=firstframe
particle(myparticle).lastframe=lastframe
particle(myparticle).duration=duration
particle(myparticle).dx=dx
particle(myparticle).dy=dy
particle(myparticle).ax=ax
particle(myparticle).ay=ay
particle(myparticle).ybounce=ybounce
particle(myparticle).angle=angle
particle(myparticle).dangle=dangle
particle(myparticle).blendmode=blendmode
particle(myparticle).r=r
particle(myparticle).g=g
particle(myparticle).b=b
particle(myparticle).a=a
particle(myparticle).dalpha=dalpha
particle(myparticle).text=text

particle(myparticle).elapsed=0
particle(myparticle).interframe=duration/(firstframe-lastframe+1)

'printdebug "myparticle=",myparticle," lastparticle=",lastparticle

end sub


sub osgl_drawparticles(byval xscene as integer=0,byval yscene as integer=0)
if lastparticle<0 then exit sub
myscreen.virgin=1
for i As Integer=maxparticle to 0 step -1
if particle(i).elapsed>particle(i).duration or particle(i).a<particle(i).dalpha or particle(i).xscale=0 or particle(i).yscale=0 then
    particle(i).exist=0
	particle(i).text=""
    if i=lastparticle then lastparticle-=1
else
    if particle(i).exist<>0 then
    particle(i).elapsed+=1
    particle(i).elapsed+=1
    particle(i).x+=particle(i).dx
    particle(i).y+=particle(i).dy
    particle(i).z+=particle(i).dz
    particle(i).dx+=particle(i).ax
    particle(i).dy+=particle(i).ay
    particle(i).dz+=particle(i).az
    particle(i).xscale+=particle(i).dxscale
    osgl_range(particle(i).xscale,0.0,9999.0)
    particle(i).yscale+=particle(i).dyscale
    osgl_range(particle(i).yscale,0.0,9999.0)
    particle(i).valpha=particle(i).a
    particle(i).valpha-=particle(i).dalpha
    particle(i).a=particle(i).valpha
    particle(i).angle+=particle(i).dangle
    if particle(i).ybounce<>-9999 then
    if particle(i).y>=particle(i).ybounce then
        particle(i).y=particle(i).ybounce-1
        particle(i).dy=-abs(0.8*particle(i).dy)
    end if
    end if
    'osgl_Render(    x1,y1,xcenter,ycenter,_
    '        z,_
    '        texturenumber,frame,_
    '        angle,_
    '        xscale,yscale,xoffset,yoffset,_
    '        xstretch,ystretch,_
    '        mirror,flipp,_
    '        xrep,yrep,xscroll,yscroll,_
    '        blendmode,depthtest,_
    '        r,g,b,a)

    'if particle(i).xslices=0 then particle(i).xslices=1:particle(i).firstframe=0
    'if particle(i).yslices=0 then particle(i).yslices=1:particle(i).firstframe=0

    if myscreen.useopengl=1 or cint(rnd)=1 then
    'printconsole "IDSIFJFIDSISD=",particle(i).z
			if particle(i).text<>"" then
				osgl_print (particle(i).x-xscene, particle(i).y-yscene, particle(i).z, particle(i).text, particle(i).xscale, particle(i).yscale, 1, particle(i).blendmode, rgba(particle(i).r,particle(i).g,particle(i).b,particle(i).a), -1, particle(i).texture)
			else
				osgl_Render(    particle(i).x-xscene,particle(i).y-yscene,0,0,_
                particle(i).z,_
                particle(i).texture,particle(i).firstframe,_
                particle(i).angle,_
                particle(i).xscale,particle(i).yscale,0,0,_
                1,1,_
                particle(i).mirror,particle(i).flipp,_
                1,1,1,1,_
                particle(i).blendmode,0,_
                rgba(particle(i).r,particle(i).g,particle(i).b,particle(i).a),-1)
                'particle(i).r,particle(i).g,particle(i).b,particle(i).a)

			end if

    end if

    end if
end if
next i
end sub

sub osgl_loadtexturePNG2(byref texturenumber as integer, byval filename as string)
if texturenumber=0 then texturenumber=osgl_freetexture

myscreen.currenttexture=0

'le textura diretamente de PNG
'Dim Texture As GLuint=0

if texturearray(texturenumber).number>-1 then osgl_deletetexture(texturenumber)

osgl_inittexture(texturenumber)

png_dimensions( filename, texturearray(texturenumber).xsize, texturearray(texturenumber).ysize )

texturearray(texturenumber).filename=filename
texturearray(texturenumber).imagedata = png_load(filename, PNG_TARGET_OPENGL)

'dim as any ptr jao=imagecreate (texturearray(texturenumber).xsize, texturearray(texturenumber).ysize)
'put jao,(0,0),texturearray(texturenumber).imagedata,pset
'texturearray(texturenumber).imagedata = jao

texturearray(texturenumber).ispng=1

If texturearray(texturenumber).imagedata=0 Then
'do whatever here because the image loading failed...
printconsole "PNG : error loading "+filename

else

    if myscreen.useopengl then
        #IFNDEF _osgl_softrender_

        GlEnable( GL_TEXTURE_2D )
        GlGenTextures( 1, @texturearray(texturenumber).number )
        glBindTexture(GL_TEXTURE_2D, texturearray(texturenumber).number )
        glTexImage2D GL_TEXTURE_2D, 0, myscreen.textureformat, texturearray(texturenumber).xsize, texturearray(texturenumber).ysize,0, GL_RGBA, GL_UNSIGNED_BYTE, texturearray(texturenumber).imagedata

        glTexParameterf GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR'_MIPMAP_LINEAR
        glTexParameterf GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR'_MIPMAP_LINEAR
        'glTexParameterf GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
	'glTexEnvi(GL_TEXTURE_ENV,GL_RGB_SCALE,0.2)
        #endif

        'imagedestroy texturearray(texturenumber).imagedata
        'deallocate texturearray(texturenumber).imagedata
        if texturearray(texturenumber).imagedata then png_destroy texturearray(texturenumber).imagedata : texturearray(texturenumber).imagedata=0

        'optionally, you can build mipmaps...
        'gluBuild2DMipmaps Gl_Texture_2D, GL_RGBA,_
        '        SprWidth, SprHeight, GL_RGBA,_
        '        GL_UNSIGNED_BYTE, Buffer
    else
	texturearray(texturenumber).filename=filename
        texturearray(texturenumber).imagedata=PNG_Load(filename,PNG_TARGET_FBNEW)
    end if

    osgl_SetTextureFrames (texturenumber,1,1,1)
End If

end sub

sub osgl_disableaudio()
	#ifndef _osgl_nosound_
		printdebug "Audio : Disabled!"
	#endif
    sound.disabled=1:sound.music_on=0:sound.sfx_on=0
end sub

sub osgl_enableaudio()
#ifndef _osgl_nosound_
    printdebug "Audio : Enabled!"
    sound.disabled=0
#endif
end sub

sub osgl_enabledebug()
    printconsole "Debug : Enabled!"
    debug=1
end sub

sub osgl_disabledebug()
    printconsole "Debug : Disabled!"
    debug=0
end sub

sub osgl_initaudio()
#ifdef _osgl_nosound_
    exit sub
#endif
if sound.disabled=1 then
    printconsole "Audio : Audio is disabled!"
    exit sub
end if
if sound.started=1 then
    printconsole "Audio  : Already initialized!"
    exit sub
end if
'----------------------------------------dynamic SDL
#IFNDEF _SDL_LINK_
if libsdl=0 or libsdlmixer=0 then
    printconsole "Audio : SDL is NOT loaded! Sound disabled!"
    sound.disabled=1:sound.music_on=0:sound.sfx_on=0
else
    printconsole "Audio : SDL is loaded!"
end if

#ENDIF
'----------------------------------------dynamic SDL

sound.music_on=1:sound.sfx_on=1
if InStr(lcase$(command$()), "-nosound") then sound.disabled=1:sound.music_on=0:sound.sfx_on=0
if InStr(lcase$(command$()), "-nomusic") then sound.music_on=0
if InStr(lcase$(command$()), "-nosfx") then sound.sfx_on=0
#ifdef _osgl_nomusic_
	sound.music_on=0
#endif
if sound.disabled=1 then
	sound.music_on=0:sound.sfx_on=0
	exit sub
end if

    sound.music = NULL
    for i As Integer=0 to lastsfx
        soundsfx(i) = NULL
    next i
    ' We're going to be requesting certain things from our audio
    ' device, so we set them up beforehand
    sound.audio_rate = 44100
    sound.audio_format = MIXER_DEFAULT_FORMAT
    sound.audio_channels = 2
    sound.audio_buffers = 4096
    sound.audio_mixchannels = 10

if sound.sfx_on or sound.music_on then
    printconsole "Audio : Initializing . . . ";
    SDL_Init(SDL_INIT_AUDIO or SDL_INIT_JOYSTICK)
    ' ' Mix_OpenAudio(int frequency, Uint16 format, int channels, int chunksize)
    if (Mix_OpenAudio(sound.audio_rate, sound.audio_format, sound.audio_channels, sound.audio_buffers)) then
           printconsole "Audio : Mix_OpenAudio ERROR - Unable to open audio!"
           osgl_disableaudio()
    else
        printconsole "OK!"
        Mix_QuerySpec(@sound.audio_rate, @sound.audio_format, @sound.audio_channels)
	printconsole "Audio : rate="+str(sound.audio_rate)+" channels="+str(sound.audio_channels)+" format="+str(sound.audio_format)
	Mix_AllocateChannels(sound.audio_mixchannels)
	sound.audio_mixchannels=Mix_AllocateChannels(-1)
	printconsole "Audio : "+str(sound.audio_mixchannels)+" mix channels allocated."
    end if
else
    printconsole "Audio is disabled - Skipping!"
end if
sound.started=1
sound.useSDL=1
end sub

sub osgl_stopmusic()
#ifdef _osgl_nosound_
    exit sub
#endif
if sound.music_on then
    if sound.music then
        Mix_HaltMusic()
        printdebug "Music : stopped"
		sound.musicplaying=0
    end if
else
       printdebug "Music : stop : Music is OFF"
end if
end sub

sub osgl_deletemusic()
#ifdef _osgl_nosound_
    exit sub
#endif
if sound.music_on then
    if sound.music then
        Mix_HaltMusic()
        Mix_FreeMusic(sound.music)
        sound.music=NULL
        printdebug "Music : unloaded "
		sound.musicfile=""
		sound.musicplaying=0
    end if
else
       printdebug "Music : unload : Music is OFF"
end if
end sub

sub osgl_loadmusic(byval filename as string)
if osgl_fileexist(filename)=0 or sound.musicfile=filename then exit sub
#ifdef _osgl_nosound_
    exit sub
#endif
'le musica
if sound.started=0 then osgl_initaudio()
if sound.music_on then
    if sound.music then osgl_deletemusic()
    sound.music = Mix_LoadMUS(filename)
    printdebug "Music : Loaded "+filename
	sound.musicfile=filename
	sound.musicplaying=0
    'Mix_LoadMUS_RW
        'Mix_PlayMusic(sound.music, -1)
else
       printdebug "Music : OFF : "+filename+" not loaded"
end if
end sub

sub osgl_playmusic(byval loops as integer=-1)
#ifdef _osgl_nosound_
    exit sub
#endif
if sound.music_on then
       printdebug "Music : I will play now..."
        Mix_PlayMusic(sound.music, loops)
	Mix_VolumeMusic(128*sound.musicvolume)
	printdebug "Music : Playing!"
	sound.musicplaying=1
else
       printdebug "Music : Play : Music is OFF"
end if
end sub

function osgl_musicisplaying as integer
function=sound.musicplaying
end function

sub osgl_deletesound(byval number as integer=-1)
#ifdef _osgl_nosound_
    exit sub
#endif
if number<0 then
    for i as integer=0 to lastsfx
        osgl_deletesound(i)
    next i
    redim soundsfx(lastsfx) as Mix_Chunk ptr
    exit sub
end if
if sound.sfx_on then
    if soundsfx(number) then
        Mix_FreeChunk(soundsfx(number))
        soundsfx(number)=0
        printdebug "Sound : unloaded "+str(number)
    end if
else
       printdebug "Sound : unload : SFX is OFF"
end if
end sub

function osgl_FreeSound as integer
'if number=0 then number=osgl_freesound
for i as integer=1 to maxsfx
    if i>lastsfx then
        printdebug "Sound : assigning sfx "+str(i)
        return i
    end if
    if soundsfx(i)=0 then
        printdebug "Sound : assigning sfx "+str(i)
        return i
    end if
next i
end function


sub osgl_loadsound(byref number as integer, byval filename as string)
if osgl_fileexist(filename)=0 then exit sub
#ifdef _osgl_nosound_
    exit sub
#endif
if sound.started=0 then osgl_initaudio()
if number=0 then number=osgl_freesound
if number>maxsfx then printconsole "Sound : could not load (sound number>maxsfx)":exit sub
if number>lastsfx then
    lastsfx=number
    redim preserve soundsfx(lastsfx) as Mix_Chunk ptr
end if
'le som
if sound.sfx_on then
    if soundsfx(number) then
		Mix_FreeChunk(soundsfx(number))
		printdebug "Sound : Deleted "+str(number)
		soundsfx(number)=0
	end if
    soundsfx(number)=Mix_LoadWAV(filename)
    printdebug "Sound : Loaded "+filename
    'Mix_LoadWAV_RW
else
       printdebug "Sound : SFX OFF : "+filename+" not loaded"
end if
end sub

sub osgl_PlaySound(byval number as integer=0,byval leftvolume as integer=255, byval rightvolume as integer=255,byval channel as integer=-1,byval loops as integer=0)
if channel>-1 then
	'alocar canais manualmente : do ultimo para o primeiro
	channel=osgl_soundchannels-channel
end if
dim as integer playingchannel
#ifdef _osgl_nosound_
    exit sub
#endif
if sound.sfx_on then
    playingchannel=Mix_PlayChannel(channel,soundsfx(number), loops) 'channel,sound,loops
    Mix_SetPanning(playingchannel,leftvolume*sound.sfxvolume,rightvolume*sound.sfxvolume)
else
       printdebug "Sound : Play : SFX is OFF!!!"
end if
end sub

sub osgl_PlaySound3D(byval number as integer=0,byval x as single=0,byval y as single=0,byval z as single=0,byval channel as integer=-1,byval loops as integer=0)
'x : -1=left   1=right
'dim as single far2=far/2
'dim as single distancerate=sqr(x^2+y^2+z^2)/far
'dim as single panrate=osgl_range(x,-far2,far2)/far2
'dim as integer panleft=osgl_range(0,255,distancerate*(128-127*panrate))
'dim as integer panright=osgl_range(0,255,distancerate*(128+127*panrate))
'osgl_PlaySound number,panleft,panright,channel,loops
if z<0 then z=0
dim as single distancerate=1-z/myscreen.far
osgl_range(distancerate,0.0,1.0)
dim as single xl=2*x/myscreen.x
osgl_range(xl,-3.0,1.0)
dim as single xr=2*x/myscreen.x
osgl_range(xr,-1.0,3.0)
dim as single xlrate,xrrate
if xl>-1 then xlrate=(1-xl)/2 else xlrate=(3+xl)/2
if xr<1 then xrrate=(1+xr)/2 else xrrate=(3-xr)/2
'printconsole "SOUND",str(x),str(xlrate),str(xrrate),str(distancerate)
osgl_PlaySound number,xlrate*255*distancerate,xrrate*255*distancerate,channel,loops
end sub


sub osgl_clear()
printdebug "System : osgl_clear"
'redim osgl_playerinput(1 to maxplayer) as playerinputtype
myscreen.FadeInalpha=0
playerinputstarted=0
currenttexture=0
myscreen.frameskipcounter=0
myscreen.fpstimer=0
myscreen.fps=myscreen.mysyncrate
myscreen.fpscounter=myscreen.mysyncrate
osgl_camera()
osgl_clearparticles()
osgl_deletetexture()
osgl_deletesound()
osgl_deletemusic()
osgl_light(0)
osgl_fog(0)
osgl_cls()
osgl_pollosevents
#IFNDEF _osgl_softrender_
glPopAttrib
#ENDIF
redim texturearray(1 to maxtexture) as texturetype
redim soundsfx(lastsfx) as Mix_Chunk ptr
redim sprite(1 to lastsprite) as osgl_spritetype
end sub

sub osgl_texturetext(byref texturenumber as integer, byval textlength as uinteger=16, byval textlines as uinteger=1,byval text as string="", byval textcolor as uinteger=rgba(255,255,255,255), byval font as any ptr=0,byval fontsize as uinteger=2)
if texturenumber=0 then texturenumber=osgl_freetexture
if text=texturearray(texturenumber).currenttext then exit sub else texturearray(texturenumber).currenttext=text
dim as uinteger x=makePOT(textlength*8)
dim as uinteger y=makePOT(textlines*16)
dim as string parsetext
parsetext=StringFromList(text,1,chr(10))
'parsetext=mid(parsetext,1,len(parsetext)-1)
if texturearray(texturenumber).number>-1 then
    if texturearray(texturenumber).xsize<>x or texturearray(texturenumber).ysize<>y then osgl_deletetexture(texturenumber)
end if
texturearray(texturenumber).xsize=x
texturearray(texturenumber).ysize=y
osgl_SetTextureFrameSize (texturenumber,x,y)

if texturearray(texturenumber).imagedata=0 then texturearray(texturenumber).imagedata=imagecreate(texturearray(texturenumber).xsize,texturearray(texturenumber).ysize,rgba(0,0,0,0),32) 'nao usar screendepth. precisa ser 32 bits de cores.
'set font size
if myscreen.currentfontsize<>fontsize then
    select case as const fontsize
        case 0:fontsize=8
        case 1:fontsize=14
        case else:fontsize=16
    end select
'    Width myscreen.realx\8, myscreen.realy\fontsize
    myscreen.currentfontsize=fontsize
end if

'Draw String [buffer,] [STEP] (x, y), text [,color [, font [, method [, (alpha|blender) ] ] ] ]

line texturearray(texturenumber).imagedata,(0,0)-(x-1,y-1),0,bf

for ii as integer=1 to textlines
    draw string texturearray(texturenumber).imagedata,(2,(ii-1)*16+2),parsetext,rgba(0,0,0,255),,PSET 'text shadow
    draw string texturearray(texturenumber).imagedata,(1,(ii-1)*16+1),parsetext,RGBA2BGRA(textcolor),,PSET
    parsetext=StringFromList(text,ii+1,chr(10))
    if parsetext="" then exit for
next ii
'if fontsize<>16 then Width myscreen.realx\8, myscreen.realy\16


if myscreen.useopengl then
    glUploadBGRATexture(texturearray(texturenumber).number, texturearray(texturenumber).imagedata,,myscreen.filter)
    'imagedestroy(texturearray(texturenumber).imagedata)
    'texturearray(texturenumber).imagedata=0
end if
osgl_SetTextureFrames (texturenumber,1,1,1)
end sub

sub osgl_setvsync(byval value as integer)
select case value
    case 1:printconsole "OpenGL : setting VSYNC ON..."
    case 0:printconsole "OpenGL : setting VSYNC OFF..."
    case else:printconsole "OpenGL : not changing VSYNC":exit sub
end select

Dim SwapInterval As Function(ByVal interval As Integer) As Integer

'GLX_SGI_swap_control
'glXSwapIntervalSGI
SwapInterval = ScreenGLProc("glXSwapIntervalSGI")
If (SwapInterval <> 0) Then
    printconsole "OpenGL : VSYNC : glXSwapIntervalSGI : OK"
        SwapInterval(value)
    exit sub
else
    printconsole "OpenGL : VSYNC : glXSwapIntervalSGI : NOT AVAILABLE"
End If

SwapInterval = ScreenGLProc("glXSwapIntervalEXT")
If (SwapInterval <> 0) Then
    printconsole "OpenGL : VSYNC : glXSwapIntervalEXT : OK"
        SwapInterval(value)
    exit sub
else
    printconsole "OpenGL : VSYNC : glXSwapIntervalEXT : NOT AVAILABLE"
End If

SwapInterval = ScreenGLProc("glXSwapIntervalMESA")
If (SwapInterval <> 0) Then
    printconsole "OpenGL : VSYNC : glXSwapIntervalMESA : OK"
        SwapInterval(value)
    exit sub
else
    printconsole "OpenGL : VSYNC : glXSwapIntervalMESA : NOT AVAILABLE"
End If

SwapInterval = ScreenGLProc("wglSwapIntervalEXT")
If (SwapInterval <> 0) Then
    printconsole "OpenGL : VSYNC : wglSwapIntervalEXT : OK"
    SwapInterval(value)
    exit sub
else
    printconsole "OpenGL : VSYNC : wglSwapIntervalEXT : NOT AVAILABLE"
End If

end sub


Function str_tok(searchStr As String,delimiterStr As String) As String

    Static As String saveStr,c
    Static As Integer saveLength,startPos
    Dim As Integer tokLength

    If searchStr = "" Then
        If saveStr = "" Then Return ""
    Else
        saveStr = searchStr
      saveLength = Len(saveStr)
      startPos = 1
    End If

    Do While startPos + tokLength <= saveLength
        c = Mid(saveStr, startPos + tokLength, 1)
        If Instr(delimiterStr, c) Then
            If tokLength Then Exit Do
            startPos += 1
        Else
            tokLength += 1
        End If
    Loop

    Function = Mid(saveStr, startPos, tokLength)

    startPos += tokLength

End Function

Function StringFromList( s1 As String, Byval index As Integer=1, separator as string="," ) As String
    Dim As Zstring Ptr p
    Dim As String temp = s1
	StringReplace s1,separator,left(separator,1)
    'Dim As Zstring*5 del = Chr(9) & Chr(10) & Chr(13) & Chr(32)
    dim as Zstring*2 del = separator
    p = strtok( Strptr(temp), @del )
    For i As Integer = 1 To index+1
      If p <> 0 And i = index Then Return *p
      p = strtok( 0, @del )
    Next
    Return ""
End Function

function StringFromList2(byval list as string,byval index as integer=1,byval separator as string=",") as string
if index<1 then return ""
dim answer as string=""
dim seppos as integer=0
dim seppos2 as integer=0
for i as integer=1 to index
    if index>1 then seppos=seppos2
    seppos2=instr(seppos2+1,list+separator,any separator+CRLF+chr(0))
    if seppos2=0 then seppos2=len(list)
    answer=mid(list,seppos+1,seppos2-seppos-1)
next i
return answer
end function

const linechars as integer=43


sub osgl_StringLineWrap(byref mystring as string, byval linelength as integer=linechars)
dim as integer linepos=0
dim as string*1 stringchar="0"

do
for i as uinteger = linelength to 0 step -1
    stringchar=mid(mystring,i+linepos,1)
    select case stringchar
        case " ":
            mystring=mid(mystring,1,i-1+linepos)+CRLF+mid(mystring,i+1+linepos,len(mystring))
            linepos+=i+1
            exit for
        case "":exit sub
    end select
next i
loop until linepos>=len(mystring)
end sub


sub StringASCII (byref mystring as string)
'dim as integer stringpos
for i as integer=1 to len(mystring)
    select case mid(mystring,i,1)
        case "ç":mystring[i-1]=135
        case "Ç":mystring[i-1]=128
        case "á":mystring[i-1]=160
        case "Á":mystring[i-1]=160
        case "â":mystring[i-1]=131
        case "Â":mystring[i-1]=131
        case "ã":mystring[i-1]=132
        case "Ã":mystring[i-1]=142
        case "à":mystring[i-1]=133
        case "À":mystring[i-1]=133
        case "é":mystring[i-1]=130
        case "É":mystring[i-1]=144
        case "ê":mystring[i-1]=136
        case "Ê":mystring[i-1]=136
        case "ó":mystring[i-1]=162
        case "Ó":mystring[i-1]=162
        case "ô":mystring[i-1]=147
        case "Ô":mystring[i-1]=147
        case "õ":mystring[i-1]=148 '148
        case "Õ":mystring[i-1]=153 '153
        case "í":mystring[i-1]=161
        case "Í":mystring[i-1]=161
        'case "í":mystring[i-1]=105
        'case "Í":mystring[i-1]=105
        case "ú":mystring[i-1]=163
        case "Ú":mystring[i-1]=163
    end select
next i
end sub


'declare function osgl_SavePNG_ (byref filename as string,byval img as FBImage ptr, byval savealpha as integer=1) as integer

sub osgl_PrepareFont(byval style as integer=3, savefont as integer=0)

myscreen.currenttexture=0

'**16x11**
' !
'0123456789:;<=>?
'@ABCDEFGHIJKLMNO
'PQRSTUVWXYZ[\]^_
'`abcdefghijklmno
'pqrstuvwxyz{|}~d
'Ç
'É
'á
'
'
if osgl_fonttexture then exit sub
dim as string aaa
dim as FBImage ptr fontimage=imagecreate(256,256,rgba(0,0,0,0),32)
dim as FBImage ptr smallfontimage=imagecreate(256,256,rgba(0,0,0,0),32)
dim as integer j=0
dim as ubyte charindex
do
for i as integer=1 to 16
'charindex=31+i+16*j
charindex=31+i+16*j
aaa=chr(charindex)
select case charindex
    case  132,148: if style=1 then draw string fontimage,((i-1)*16+4+1,j*24+4+1),"~",rgba(0,0,0,255)
                draw string fontimage,((i-1)*16+4,j*24+4),"~"
                aaa="a"

    case  142,153: if style=1 then draw string fontimage,((i-1)*16+4+1,j*24+4-2),"~",rgba(0,0,0,255)
                draw string fontimage,((i-1)*16+4,j*24+4-3),"~"
                aaa="A"
    case  135,128: if style=1 then draw string fontimage,((i-1)*16+4+1,j*24+4+2),aaa,rgba(0,0,0,255)
                draw string fontimage,((i-1)*16+4,j*24+4+1),aaa
                aaa=" "
    'case  135: draw string fontimage,((i-1)*8,j*16+1),chr(135)
    'case  161: draw string fontimage,((i-1)*8,j*16),"i" : draw string fontimage,((i-1)*8,j*16-1),"'"
end select

select case style
    case 1:	draw string fontimage,(16*(i-1)+4+1,j*24+4+1),aaa,rgba(0,0,0,255)
			draw string fontimage,(16*(i-1)+4,j*24+4),aaa

    case 2:	draw string fontimage,(16*(i-1)+4+1,j*24+4+1),aaa,rgba(0,0,0,155)
			draw string fontimage,(16*(i-1)+4,j*24+4),aaa

    case 3:	draw string fontimage,(16*(i-1)+4+1,j*24+4+1),aaa,rgba(0,0,0,105)
			draw string fontimage,(16*(i-1)+4-1,j*24+4-1),aaa,rgba(0,0,0,105)
			draw string fontimage,(16*(i-1)+4+1,j*24+4-1),aaa,rgba(0,0,0,105)
			draw string fontimage,(16*(i-1)+4-1,j*24+4+1),aaa,rgba(0,0,0,105)
			draw string fontimage,(16*(i-1)+4+1,j*24+4),aaa,rgba(0,0,0,195)
			draw string fontimage,(16*(i-1)+4-1,j*24+4),aaa,rgba(0,0,0,195)
			draw string fontimage,(16*(i-1)+4,j*24+4-1),aaa,rgba(0,0,0,195)
			draw string fontimage,(16*(i-1)+4,j*24+4+1),aaa,rgba(0,0,0,195)
		draw string fontimage,(16*(i-1)+4,j*24+4),aaa,rgba(255,255,255,245)

    case 4:	draw string fontimage,(16*(i-1)+4+1,j*24+4+1),aaa,rgba(0,0,0,255)
			draw string fontimage,(16*(i-1)+4,j*24+4),aaa,rgba(255,255,255,255)
			if style=4 then
				for jj as integer=(16*(i-1)+4) to (16*i+3)
					if point(jj,j*24+13,fontimage)=rgba(255,255,255,255) then pset fontimage,(jj,j*24+13),rgba(230,220,230,255)
					if point(jj,j*24+14,fontimage)=rgba(255,255,255,255) then pset fontimage,(jj,j*24+14),rgba(180,180,180,255)
					if point(jj,j*24+15,fontimage)=rgba(255,255,255,255) then pset fontimage,(jj,j*24+15),rgba(230,220,230,255)
				next jj
			end if


end select
next i
j+=1
aaa=""
loop until charindex>=255

'ImageBorderFilter fontimage

'salvar a fonte
'if savefont then osgl_SavePNG "/tmp/osglfont.png", fontimage, 1
if savefont then print (BSAVE("/tmp/osglfont.bmp", fontimage))

'put(0,0),fontimage,pset
'flip
'sleep
'end
get fontimage,(0,0)-(255,255),smallfontimage

imagescale2xandeagle(fontimage)
#IFNDEF _osgl_softrender_

if osgl_fonttexture=0 then osgl_fonttexture=osgl_freetexture
if texturearray(osgl_fonttexture).number>-1 then osgl_deletetexture(osgl_fonttexture)
texturearray(osgl_fonttexture).imagedata=fontimage
texturearray(osgl_fonttexture).ispng=0
ImageInfo texturearray(osgl_fonttexture).imagedata,texturearray(osgl_fonttexture).xsize,texturearray(osgl_fonttexture).ysize
if myscreen.useopengl then
    glUploadBGRATexture(texturearray(osgl_fonttexture).number, texturearray(osgl_fonttexture).imagedata,,myscreen.filter)
    if texturearray(osgl_fonttexture).imagedata then imagedestroy texturearray(osgl_fonttexture).imagedata : texturearray(osgl_fonttexture).imagedata=0 : fontimage=0
end if
osgl_SetTextureFrameSize (osgl_fonttexture,32,48)
printdebug "Font is texture "+str(osgl_fonttexture)
'fonttexture=texturearray(osgl_fonttexture).number

if osgl_smallfonttexture=0 then osgl_smallfonttexture=osgl_freetexture
if texturearray(osgl_smallfonttexture).number>-1 then osgl_deletetexture(osgl_smallfonttexture)
texturearray(osgl_smallfonttexture).imagedata=smallfontimage
texturearray(osgl_smallfonttexture).ispng=0
ImageInfo texturearray(osgl_smallfonttexture).imagedata,texturearray(osgl_smallfonttexture).xsize,texturearray(osgl_smallfonttexture).ysize
if myscreen.useopengl then
    glUploadBGRATexture(texturearray(osgl_smallfonttexture).number, texturearray(osgl_smallfonttexture).imagedata,,myscreen.filter)
    if texturearray(osgl_smallfonttexture).imagedata then imagedestroy texturearray(osgl_smallfonttexture).imagedata : texturearray(osgl_smallfonttexture).imagedata=0 : smallfontimage=0
end if
osgl_SetTextureFrameSize (osgl_smallfonttexture,16,24)
printdebug "Small font is texture "+str(osgl_smallfonttexture)
'smallfonttexture=texturearray(osgl_smallfonttexture).number

'glUploadBGRATexture (fonttexture, fontimage, 0,myscreen.filter)
'glUploadTexture (fonttexture, fontimage, 0)


    dim cx as double                             '' Holds Our X Character Coord
    dim cy as double                             '' Holds Our Y Character Coord
    dim gloop as integer

	const border as single=0.002

if glfontbase=0 then
    glfontbase = glGenLists(255)                      '' Creating 256 Display Lists
    glBindTexture GL_TEXTURE_2D, texturearray(osgl_fonttexture).number
    for gloop = 0 to 255                      '' Loop Through All 256 Lists

        cx = (gloop mod 16)/16.0                 '' X Position Of Current Character
        cy = (gloop\16)*3/32                     '' Y Position Of Current Character

                glNewList glfontbase+gloop, GL_COMPILE        '' Start Building A List
                glBegin GL_TRIANGLE_STRIP                         '' Use A Quad For Each Character
                    glTexCoord3d cx, cy+0.09375-border,0         '' Texture Coord (Top Right)
                    glVertex3f -4, -20 ,0                    '' Vertex Coord (Top Left)
                    glTexCoord3d cx, cy,0  '' Texture Coord (Bottom Right)
                    glVertex3f -4, 4 ,0                     '' Vertex Coord (Bottom Left)
                    glTexCoord3d cx+0.0625-border,cy+0.09375-border,0                '' Texture Coord (Top Left)
                    glVertex3f 12, -20,0                    '' Vertex Coord (Top Right)
                    glTexCoord3d cx+0.0625-border, cy,0       '' Texture Coord (Bottom Left)
                    glVertex3f 12, 4 ,0                    '' Vertex Coord (Bottom Right)
                glEnd                                    '' Done Building Our Quad (Character)
                glTranslated 9, 0, 0                    '' Move To The Right Of The Character  FONT SPACING
                glEndList                                '' Done Building The Display List

    next
end if

if glnehefontbase=0 then
	glnehefontbase = glGenLists(255)                      '' Creating 256 Display Lists
    glBindTexture GL_TEXTURE_2D, texturearray(osgl_fonttexture).number
	for gloop = 0 to 255                         '' Loop Through All 256 Lists

		cx = (gloop mod 16)/16.0                 '' X Position Of Current Character
		cy = (gloop\16)/16.0                     '' Y Position Of Current Character

		glNewList glnehefontbase+gloop, GL_COMPILE        '' Start Building A List
		glBegin GL_TRIANGLE_STRIP
			glTexCoord2f cx, cy+0.0625         '' Texture Coord (Bottom Left)
			glVertex3f -8, -8, 0                      '' Vertex Coord (Bottom Left)
			glTexCoord2f cx,cy                 '' Texture Coord (Top Left)
			glVertex3f -8, 8, 0                     '' Vertex Coord (Top Left)
			glTexCoord2f cx+0.0625, cy+0.0625  '' Texture Coord (Bottom Right)
			glVertex3f 8,-8, 0                      '' Vertex Coord (Bottom Right)
			glTexCoord2f cx+0.0625, cy         '' Texture Coord (Top Right)
			glVertex3f 8, 8, 0                    '' Vertex Coord (Top Right)
		glEnd                                    '' Done Building Our Quad (Character)
		glTranslated 10, 0, 0                    '' Move To The Right Of The Character
		glEndList                                '' Done Building The Display List
	next
end if

if glhalfnehefontbase=0 then
	glhalfnehefontbase = glGenLists(255)                      '' Creating 256 Display Lists
    glBindTexture GL_TEXTURE_2D, texturearray(osgl_fonttexture).number
	for gloop = 0 to 255                         '' Loop Through All 256 Lists

		cx = (gloop mod 16)/16.0                 '' X Position Of Current Character
		cy = (gloop\16)/8.0                     '' Y Position Of Current Character

		glNewList glhalfnehefontbase+gloop, GL_COMPILE        '' Start Building A List
		glBegin GL_TRIANGLE_STRIP
			glTexCoord2f cx, cy+0.125         '' Texture Coord (Bottom Left)
			glVertex3f -8, -8, 0                      '' Vertex Coord (Bottom Left)
			glTexCoord2f cx,cy                 '' Texture Coord (Top Left)
			glVertex3f -8, 8, 0                     '' Vertex Coord (Top Left)
			glTexCoord2f cx+0.0625, cy+0.125  '' Texture Coord (Bottom Right)
			glVertex3f 8,-8, 0                      '' Vertex Coord (Bottom Right)
			glTexCoord2f cx+0.0625, cy         '' Texture Coord (Top Right)
			glVertex3f 8, 8, 0                    '' Vertex Coord (Top Right)
		glEnd                                    '' Done Building Our Quad (Character)
		glTranslated 10, 0, 0                    '' Move To The Right Of The Character
		glEndList                                '' Done Building The Display List
	next
end if

#ENDIF
end sub



sub osgl_Print(byval x as single=0, byval y as single=0, byval z as single=0, byval printstring as string,byval xscale as single=1,byval yscale as single=1,centered as integer=0,byval blendmode as integer=1,byval colour as uinteger=rgba(255,255,255,255),byval orientation as integer=-1, byval altfont as integer=0, byval nehefont as integer=0)
if printstring="" then exit sub
y=-y
z=-z
myscreen.virgin=1
'osgl_Print(x,y,z,printstring,xscale,yscale,centered,blendmode,r,g,b,a)
dim as string glstring=printstring
stringASCII(glstring)

dim as string glstringarray()
String2Array(glstring,CRLF,glstringarray())

if myscreen.useopengl=0 then
'Draw String [buffer,] [STEP] (x, y), text [,color [, font [, method [, (alpha|blender) ] ] ] ]
    draw string (x,y),glstring,colour
    exit sub
end if

    #IFNDEF _osgl_softrender_

if osgl_fonttexture=0 then osgl_PrepareFont


dim as single xratio=myscreen.x/myscreen.realx
dim as single yratio=myscreen.y/myscreen.realy

'choose font
	if altfont=0 then
		if xscale<=xratio andalso yscale<=yratio then
			if myscreen.currenttexture<>texturearray(osgl_smallfonttexture).number then osgl_bindtexture texturearray(osgl_smallfonttexture).number
		else
			if myscreen.currenttexture<>texturearray(osgl_fonttexture).number then osgl_bindtexture texturearray(osgl_fonttexture).number
		end if
	else
		if myscreen.currenttexture<>texturearray(altfont).number then osgl_bindtexture texturearray(altfont).number
	end if

    glDisable GL_DEPTH_TEST
    glEnable GL_TEXTURE_2D
	osgl_SetBlendMode(blendmode)
	dim mycolour as colortype
	mycolour.colour=colour
	glColor4ub mycolour.r,mycolour.g,mycolour.b,mycolour.a

dim as single x0=x

for textline as integer=lbound(glstringarray) to ubound(glstringarray)

x=x0

if centered then x=x-(xscale*len(glstringarray(textline))*4.5)

	for i as integer=0 to myscreen.stereo3d

       if myscreen.stereo3d and myscreen.drawingtotexture=0 then
	 if i=0 then
		'glColor4ub r,0,0,a
		'osgl_set3dcoords
		glColorMask(GL_TRUE,GL_FALSE,GL_FALSE,GL_FALSE)
	 else
		'glColor4ub 0,g,b,a/2
		osgl_set3dcoords(1)
		'x1-=.1*z
		glColorMask(GL_FALSE,GL_TRUE,GL_TRUE,GL_FALSE)
	 end if
	end if

		glTranslated x, y+21*yscale*(1-textline), z+myscreen.eyez                                    '' Position The Text (0,0 - Bottom Left)

select case orientation

case 1:	'cone billboard
		glScalef xscale,yscale,1.0
		glrotatef myscreen.cameraya,0,1,0

case -1:	'spherical billboard
		'glrotatef myscreen.cameraya,0,1,0
		'glrotatef myscreen.cameraxa,-1,0,0

		dim as glfloat modelview(15)
		glGetFloatv(GL_MODELVIEW_MATRIX , @modelview(0))
		for ii as integer=0 to 2
			for jj as integer=0 to 2
				if ii=jj then
					modelview(ii*4+jj) = 1.0
				else
					modelview(ii*4+jj) = 0.0
				end if
			next jj
		next ii
		glLoadMatrixf(@modelview(0))
		glScalef xscale,yscale,1.0
		'glScalef xstretch,ystretch,1.0

case else: glScalef xscale,yscale,1.0


end select

	select case as const nehefont
		case 1,2
			glListBase glnehefontbase-32+(128*(nehefont-1))                          '' Choose The Font Set (0 or 1)
			glCallLists len(glstringarray(textline)),GL_UNSIGNED_BYTE, strptr(glstringarray(textline))     '' Write The Text To The Screen
		case 3
			glListBase glhalfnehefontbase-32
			glCallLists len(glstringarray(textline)),GL_UNSIGNED_BYTE, strptr(glstringarray(textline))     '' Write The Text To The Screen
		case else
			glListBase glfontbase-32
			glCallLists len(glstringarray(textline)),GL_UNSIGNED_BYTE, strptr(glstringarray(textline))     '' Write The Text To The Screen
	end select

	next i

	'glpopmatrix
	osgl_set3dcoords
next textline

'glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_FALSE)
glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE)
'osgl_set3dcoords

#endif

end sub


sub FLCopen (byval FLCFileName as string)

dim as string filename : filename=FLCFileName

if osgl_fileexist(filename)=0 then exit sub

if flcFileNum<>0 then
	close #flcFileNum
	printdebug "****** FILE CLOSED: #"+str(flcfilenum)
end if

flcFileNum=freefile2()

OPEN FileName FOR BINARY access Read AS #flcFileNum
printdebug "FILE OPEN: #"+str(flcfilenum)

'--- Get the File's flcHeader ---
GET #flcFileNum, , flcHeader

CLOSE #flcFileNum
printdebug "FILE CLOSED: #"+str(flcfilenum)
flcFileNum=0


dim as uinteger xsize,ysize
if flcuseopengl then
    xsize=makePOT(flcHeader.Xres)
    ysize=makePOT(flcHeader.Yres)
    'ysize=makePOT(flcHeader.Yres+1)
else
    xsize=flcHeader.Xres
    'ysize=flcHeader.Yres+1
    ysize=flcHeader.Yres
end if


'create image buffer
flcbuffer=imagecreate(xsize,ysize,rgba(0,0,0,0),flcscreendepth)
imageinfo flcbuffer,xsize,ysize,,flcpitch,flcbufferpixels
flcpitch=flcpitch/4

if flcFileNum<>0 then
	close #flcFileNum
	printdebug "****** FILE CLOSED: #"+str(flcfilenum)
end if
flcFileNum=freefile2()

OPEN FileName FOR BINARY access Read AS #flcFileNum
printdebug "FILE OPEN: #"+str(flcfilenum)

'--- Get the File's flcHeader ---
GET #flcFileNum, , flcHeader

    IF flcHeader.ID <> &HAF11 AND flcHeader.ID <> &HAF12 THEN
        'print "flic is ",&HAF11,"or", &HAF12
        'print flcHeader.ID,"is not flic"
		CLOSE #flcFileNum
		printdebug "FILE CLOSED: #"+str(flcfilenum)
		flcFileNum=0
        EXIT SUB
    END IF



end sub



function FLCrendernextframe() as any ptr
'flcuseopengl=0
'flcscreendepth=32
'print "nextframe"

dim flcFramePos as uinteger
dim flcDataPos as uinteger
dim flcLinePos as uinteger
dim flcChunk as ushort
dim Index as ushort
dim PacketNum as ushort
dim StartLine as ushort
dim NumLines as ushort
dim StartByte as ushort
dim PacketByte as ushort
dim PixelByte as ubyte
dim PixelByte1 as ubyte
dim PixelByte2 as ubyte
dim PixelWord as ushort
dim SkipByte as ubyte
dim ChangeByte as ushort
dim SizeByte as ubyte
dim Word as ushort
dim WordType as ushort
dim PacketCount as ushort
dim LastPixel as ushort
dim RedByte as ubyte
dim GreenByte as ubyte
dim BlueByte as ubyte
dim AlphaByte as ubyte

dim X as ushort=0
dim Y as ushort=0
dim X1 as ushort=0
dim Y1 as ushort=0
dim A as ushort=0
dim B as ushort=0

DIM mybyte2 AS ubyte=0
dim tamtam as uinteger=0
dim tamtam2 as uinteger=0


        flcFramePos = LOC(flcFileNum)        '<-- Needed? --
        GET #flcFileNum, , flcFrameflcChunk

'print "correct id is",&HF1FA
'print "read id is",flcFrameflcChunk.ID
'sleep
'print "press any key"

        IF flcFrameflcChunk.ID = &HF1FA THEN

            FOR flcChunk = 1 TO flcFrameflcChunk.flcChunks

                'print "1+LOC",loc(flcfilenum)
                flcDataPos = LOC(flcFileNum)        '<-- Needed? -- << v1.1 >>
                GET #flcFileNum, , flcDataChunk
                'SEEK flcFileNum, loc(flcfilenum)-1 'this is required after fb 0.20 (why?!?!?!?!?!)
                'print "2+LOC",loc(flcfilenum)



                SELECT CASE flcDataChunk.ID
                 CASE 4, 11        '--*-- COLOR256/COLOR64: Change Palette --*--
                'print "case 4,11"


                    index = 0
                    GET #flcFileNum, , packetnum
                    'print "***packetnum",packetnum
                    'if packetnum=0 then packetnum=1 'teste!!!!
                    FOR A = 1 TO packetnum
                        GET #flcFileNum, , skipbyte
                        GET #flcFileNum, , mybyte2: changebyte = mybyte2
                        index = index + skipbyte
                        IF changebyte = 0 THEN changebyte = 256
                        FOR B = 1 TO changebyte
                            'GET #flcFileNum, , mybyte2: RedByte = mybyte2
                        '    GET #flcFileNum, , mybyte2: GreenByte = mybyte2
                        '    GET #flcFileNum, , mybyte2: BlueByte = mybyte2
                            GET #flcFileNum, , RedByte
                            GET #flcFileNum, , GreenByte
                            GET #flcFileNum, , BlueByte
                            'print "pal:",RedByte,GreenByte,BlueByte
                            'print "bytes read=",tamtam
                            'print "get result=",tamtam2
                            IF flcDataChunk.ID = 4 THEN
                                if flcscreendepth>8 then
                                    AlphaByte=255
                                    'if flcusetransparency then
                                    'if flctransparentcolor=rgba(RedByte,GreenByte,BlueByte,255) then
                                    '    if flcscreendepth=16 then RedByte=255:GreenByte=0:BlueByte=255 else AlphaByte=0
                                    'end if
                                    'end if
'                                    flcPalette(Index)=rgba(RedByte,GreenByte,BlueByte,255*(flctransparentcolor<>rgb(RedByte,GreenByte,BlueByte)))
                                    if flcuseopengl then swap RedByte,BlueByte
                                    flcPalette(Index)=rgba(RedByte,GreenByte,BlueByte,AlphaByte)
                                    'flcPalette(Index)=rgb(RedByte,GreenByte,BlueByte)
                                else
                                    flcPalette(Index)=Index
                                    palette Index,RedByte,GreenByte,BlueByte
                                end if
                                'print "palette"
'                                palette Index,RedByte \ 4,GreenByte \ 4,BlueByte \ 4
                            ELSE
                                if flcscreendepth>8 then
                                    AlphaByte=255
                                    'if flcusetransparency then
                                    'if flctransparentcolor=rgba(RedByte,GreenByte,BlueByte,255) then
                                    '    if flcscreendepth=16 then RedByte=255:GreenByte=0:BlueByte=255 else AlphaByte=0
                                    '    RedByte=255:GreenByte=0:BlueByte=255:AlphaByte=0
                                    'end if
                                    'end if
'                                    flcPalette(Index)=rgba(RedByte,GreenByte,BlueByte,255*(flctransparentcolor<>rgb(RedByte,GreenByte,BlueByte)))
                                    if flcuseopengl then swap RedByte,BlueByte
                                    flcPalette(Index)=rgba(RedByte,GreenByte,BlueByte,AlphaByte)
                                    'flcPalette(Index)=rgb(RedByte,GreenByte,BlueByte)
                                else
                                    flcPalette(Index)=Index
                                    palette Index,RedByte,GreenByte,BlueByte
                                end if
                                'print "palette"
                            END IF
                            index = index + 1
                        NEXT B
                    NEXT A
                    'print palette
                    'for i as integer=0 to 255:print flcPalette(i);:next i
                    if flcusetransparency then
                        'sleep
                        select case flcscreendepth
                            case 8: flcPalette(0)=0
                            case 16: flcPalette(0)=rgb(255,0,255)
                            case else: flcPalette(0)=rgba(0,0,0,0) '0000
                        end select
                    end if

                 CASE 12           '--*-- LC: Byte Aligned Delta Compression --*--

                    GET #flcFileNum, , StartLine
                    GET #flcFileNum, , mybyte2: NumLines = mybyte2
'                    flcLinePos = StartLine * flcHeader.Xres&
                    flcLinePos = StartLine * 320&
                    GET #flcFileNum, , mybyte2: StartByte = mybyte2
                    FOR Y = 0 TO NumLines-1
                        GET #flcFileNum, , mybyte2: PacketByte = mybyte2
                        X = StartByte
                        FOR A = 1 TO PacketByte
                            GET #flcFileNum, , skipbyte
                            GET #flcFileNum, , SizeByte
                            X = X + skipbyte
                            IF SizeByte > 127 THEN
                                SizeByte = -(SizeByte OR &HFF00)
                                GET #flcFileNum, , pixelbyte
                                FOR B = 1 TO SizeByte
'                                    POKE flcLinePos + X, pixelbyte
                                    'Y1=flcLinePos\flcHeader.Xres '-52431
                                    'Y1=flcLinePos\320-52431
                                    Y1=flcLinePos\320-52428
				    if Y1>flcHeader.Yres then Y1-=13108
                                    'print "pixel"
                                    'if (Y1+3)<flcHeader.Yres then PSET flcbuffer,(X,Y1+3),flcPalette(pixelbyte)
                                    'if Y1<flcHeader.Yres then flcbufferpixels[X+Y1*flcpitch]=flcPalette(pixelbyte)

                                    flcbufferpixels[X+Y1*flcpitch]=flcPalette(pixelbyte)

				    'flcbufferpixels[X+Y*flcHeader.Xres]=flcPalette(pixelbyte)
                                    X = X + 1
'                                    if X>319 then Y+=1:X-=flcHeader.Xres
                                NEXT B
                            ELSE
                                FOR B = 1 TO SizeByte
                                    GET #flcFileNum, , pixelbyte
'                                    POKE flcLinePos + X, pixelbyte
                                    'Y1=flcLinePos\flcHeader.Xres '-52431
                                    Y1=flcLinePos\320-52428
				    if Y1>flcHeader.Yres then Y1-=13108
                                    'print "pixel"
                                    'if (Y1+3)<flcHeader.Yres then PSET flcbuffer,(X,Y1+3),flcPalette(pixelbyte)
                                    'if Y1<flcHeader.Yres then flcbufferpixels[X+Y1*flcpitch]=flcPalette(pixelbyte)

                                    flcbufferpixels[X+Y1*flcpitch]=flcPalette(pixelbyte)

				    'flcbufferpixels[X+Y*flcHeader.Xres]=flcPalette(pixelbyte)
                                    X += 1
'                                    if X>319 then Y+=1:X-=flcHeader.Xres
                                NEXT B
                            END IF
                        NEXT A
                        'flcLinePos += flcHeader.Xres
                        flcLinePos += 320
                    NEXT Y
                    GET #flcFileNum, , mybyte2      '<-- Needed? --

                 CASE 7  '--*-- SS2: Word Aligned Delta Compression (FLC Only)--*--

                    flcLinePos = 0
                    GET #flcFileNum, , NumLines
                    FOR Y = 0 TO NumLines-1		' -1 ??????
                        ''LastPixel = -1    '<-- For ODD Width Flics (not used)
                        DO
                            GET #flcFileNum, , Word
                            WordType = (Word AND &HC000)
                            SELECT CASE WordType
                                CASE 0: PacketCount = Word
                                CASE &H8000: LastPixel = (Word AND &HFF)
'                                CASE &HC000: flcLinePos = flcLinePos + (Word * -flcHeader.Xres&)
                                CASE &HC000: flcLinePos = flcLinePos + (Word * -320&)
                            END SELECT
                        LOOP UNTIL WordType = 0
                        X = 0
                        FOR A = 1 TO PacketCount
                            GET #flcFileNum, , skipbyte
                            GET #flcFileNum, , SizeByte
                            X = X + skipbyte
                            IF SizeByte > 127 THEN
                                SizeByte = -(SizeByte OR &HFF00)
                                GET #flcFileNum, , PixelByte1
                                GET #flcFileNum, , PixelByte2
                                FOR B = 1 TO SizeByte
'                                    POKE flcLinePos + X, PixelByte1
                                    'Y1=flcLinePos\flcHeader.Xres '-52431
                                    'print "pixel"
                                    Y1=flcLinePos\320-52428
                                    'Y1=flcLinePos\320-52429
                                    'if (Y1+3)<flcHeader.Yres then PSET flcbuffer,(X,Y1+3),flcPalette(pixelbyte1)
                                    'if Y1<flcHeader.Yres then flcbufferpixels[X+Y1*flcpitch]=flcPalette(pixelbyte1)

				    if Y1>flcHeader.Yres then Y1-=13108

                                    flcbufferpixels[X+Y1*flcpitch]=flcPalette(pixelbyte1)

				    'flcbufferpixels[X+Y*flcHeader.Xres]=flcPalette(pixelbyte1)

'                                    POKE flcLinePos + X + 1, PixelByte2
'                                    if X>319 then x-=flcHeader.Xres:y+=1
                                    'if (Y1+3)<flcHeader.Yres then PSET flcbuffer,(X+1,Y1+3),flcPalette(pixelbyte2)
                                    'if Y1<flcHeader.Yres then flcbufferpixels[X+1+Y1*flcpitch]=flcPalette(pixelbyte2)

                                    flcbufferpixels[X+1+Y1*flcpitch]=flcPalette(pixelbyte2)

    				    'flcbufferpixels[X+1+Y*flcHeader.Xres]=flcPalette(pixelbyte2)


                                    X += 2
                                NEXT B
                            ELSE
                                FOR B = 1 TO SizeByte
                                    GET #flcFileNum, , PixelByte1
                                    GET #flcFileNum, , PixelByte2
'                                    POKE flcLinePos + X, PixelByte1
                                    'Y1=flcLinePos\flcHeader.Xres '-52431
					Y1=flcLinePos\320-52428

				    	if Y1>flcHeader.Yres then Y1-=13108

                                    'print "pixel"
'                                    print Y,Y1:sleep
'                                    if X>319 then x-=flcHeader.Xres:y+=1
                                   'if (Y1+3)<flcHeader.Yres then PSET flcbuffer,(X,Y1+3),flcPalette(pixelbyte1)
                                     'if Y1<flcHeader.Yres then flcbufferpixels[X+Y1*flcpitch]=flcPalette(pixelbyte1)

                                    flcbufferpixels[X+Y1*flcpitch]=flcPalette(pixelbyte1)

     				    'flcbufferpixels[X+Y*flcHeader.Xres]=flcPalette(pixelbyte1)
     				    'flcbufferpixels[X+flcLinePos-52431]=flcPalette(pixelbyte1)


'                                    POKE flcLinePos + X + 1, PixelByte2
                                    'if (Y1+3)<flcHeader.Yres then PSET flcbuffer,(X+1,Y1+3),flcPalette(pixelbyte2)
                                       'if Y1<flcHeader.Yres then flcbufferpixels[X+1+Y1*flcpitch]=flcPalette(pixelbyte2)

                                     flcbufferpixels[X+1+Y1*flcpitch]=flcPalette(pixelbyte2)

       				    'flcbufferpixels[X+1+Y*flcHeader.Xres]=flcPalette(pixelbyte2)


                                    X += 2
                                NEXT B
                            END IF
                        NEXT A
                        ''-- Following is for ODD Width Flics (not used) --
                        ''IF LastPixel > -1 THEN
                        ''   POKE flcLinePos + flcHeader.Xres - 1, LastPixel
                        ''END IF
                        'flcLinePos += flcHeader.Xres
                        flcLinePos += 320
                    NEXT Y

                 CASE 13           '--*-- BLACK: Black-Out Screen --*--
                    line flcbuffer,(0,0)-(flcHeader.Xres,flcHeader.Yres),rgba(0,0,0,255),BF
		    'printdebug "FLC BLACK!!!!"
                    'line flcbuffer,(0,0)-(flcHeader.Xres,flcHeader.Yres),flcpalette(0),BF
                    'CLS 0

                 CASE 15           '--*-- BRUN: Byte Run Length Compression --*--

                    flcLinePos = 0
                    'FOR Y = 0 TO NumLines-1 '199
                    FOR Y = 0 TO flcHeader.Yres-1
                        GET #flcFileNum, , mybyte2
                        X = 0
                        DO
                            GET #flcFileNum, , SizeByte
                            IF SizeByte > 127 THEN
                                SizeByte = -(SizeByte OR &HFF00)
                                FOR B = 1 TO SizeByte
                                    GET #flcFileNum, , pixelbyte
'                                    POKE flcLinePos + X, pixelbyte
'                                    Y1=flcLinePos\flcHeader.Xres-52431-13104
                                    'if X>319 then x-=flcHeader.Xres:y+=1
                                    'print "pixel"
                                    'if Y<flcHeader.Yres then PSET flcbuffer,(X,Y),flcPalette(pixelbyte)
				    'Y-=1
                                    'if Y<flcHeader.Yres-1 then flcbufferpixels[X+Y*flcpitch]=flcPalette(pixelbyte)

                                    flcbufferpixels[X+Y*flcpitch]=flcPalette(pixelbyte)

                                    X += 1
                                NEXT B
                            'ELSEIF SizeByte = 0 THEN       '*** Test ***
                            ELSE
                                GET #flcFileNum, , pixelbyte
                                FOR B = 1 TO SizeByte
'                                    POKE flcLinePos + X, pixelbyte
'                                    Y1=flcLinePos\flcHeader.Xres-52431-13104
                                    'if X>319 then x-=flcHeader.Xres:y+=1
                                    'print "pixel"
                                    'if Y<flcHeader.Yres then PSET flcbuffer,(X,Y),flcPalette(pixelbyte)
				    'Y-=1
                                    'if Y<flcHeader.Yres then flcbufferpixels[X+Y*flcpitch]=flcPalette(pixelbyte)

                                    flcbufferpixels[X+Y*flcpitch]=flcPalette(pixelbyte)

                                    X += 1
                                NEXT B
                            END IF
                        LOOP UNTIL X >= flcHeader.Xres '320
                        'flcLinePos += flcHeader.Xres '320
                        flcLinePos += 320
                    NEXT Y
                    GET #flcFileNum, , mybyte2         '<-- Needed? --

                 CASE 16           '--*-- COPY: Bitmap of Entire Image --*--

                                FOR Y = 0 TO flcHeader.Yres-1
                                FOR X = 0 TO flcHeader.Xres-1
                                    GET #flcFileNum, , pixelbyte
                                    'PSET flcbuffer,(X,Y),flcPalette(pixelbyte)
                                    flcbufferpixels[X+Y*flcpitch]=flcPalette(pixelbyte)

                                NEXT X
                                NEXT Y

                 CASE ELSE

		    'printdebug "FLC UNKNOWN!!!!"
                    'line flcbuffer,(0,0)-(flcHeader.Xres,flcHeader.Yres),rgba(0,0,0,255),BF
                    '--*-- Unknown Data flcChunk, so Skip Over --*--
		    'printdebug "unknown!!!!"

                    SEEK #flcFileNum, flcDataPos + flcDataChunk.Size + 1    '<< v1.1 >>

                END SELECT

            NEXT flcChunk

        ELSE
            '--- Unknown flcFrame flcChunk, so Skip Over ---

        END IF

        SEEK #flcFileNum, flcFramePos + flcFrameflcChunk.Size + 1     '<-- Needed? --

flcFrame+=1
if flcFrame> flcHeader.flcFrames+1 then
	CLOSE #flcFileNum
	printdebug "FILE CLOSED: #"+str(flcfilenum)
	flcFileNum=0
    'a funcao vai retornar 0 quando a animacao acabar
    if flcbuffer then
		ImageDestroy(flcbuffer)
		flcBuffer=0
	end if
    flcFrame=0
end if

return flcBuffer
'put (100,100),flcbuffer,pset
end function

SUB FLCplay (flcx as integer=0,flcy as integer=0,flcscalex as single=0,flcscaley as single=0,FileName as string,loops as integer=999,delay as double=60, byval usetransparency as integer=0, byval keyflag as integer=0)
flcusetransparency=usetransparency
Screeninfo flcoglx,flcogly,flcscreendepth,,,,flcdriver
if lcase$(flcdriver)="opengl" then flcuseopengl=1
dim buffer as any ptr
dim as double flcplaytimer1
for flcloops as integer=1 to loops
FLCopen(FileName)
do
    flcplaytimer1=timer()+delay/1000
    buffer=FLCrendernextframe
    printdebug "FLC res:"+str(flcHeader.Xres)+"X"+str(flcHeader.Yres)
    'print "buffer:";buffer
    if flcFrame>1 then
    if buffer<>0 then
        if flcuseopengl then
            #IFNDEF _osgl_softrender_
            #IFNDEF __FB_DOS__
            'osgl_box(0,0,640,480,rgba(255,255,255,255),rgba(255,255,255,255),rgba(255,0,255,255),rgba(255,0,255,255))
            if flcusetransparency=0 then
                glDisable GL_BLEND
                glClear  GL_COLOR_BUFFER_BIT OR GL_DEPTH_BUFFER_BIT
            else
                glEnable GL_BLEND
                glBlendFunc GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
            end if
            glUploadBGRATexture(flcTexture,flcbuffer,,myscreen.filter)
            glMatrixMode GL_PROJECTION
            glLoadIdentity
            glOrtho 0,flcoglx,flcogly,0,-1,1                                '' Set Up An Ortho Screen
            glMatrixMode GL_MODELVIEW
            glLoadIdentity
            glEnable GL_Texture_2D                   '' Enable 2D flcTexture Mapping
            glBindTexture GL_Texture_2D, flcTexture    '' Select flcTexture
            glTranslatef flcx,flcy,0
            glScalef flcscalex,flcscaley,0
            'glRotatef 0,0,0,0
            'gluPerspective GLdouble    fovy, GLdouble    aspect, GLdouble zNear, GLdouble zFar
            'gluPerspective 2,2,0,10
            glColor4ub 255,255,255,255
	    'glquad(0,0,0,flcHeader.Yres,flcHeader.Xres,0,flcHeader.Xres,flcHeader.Yres,_
		'	0,0,0,1,1,0,1,1)
	    glquad3d(0,0,0,0,flcHeader.Yres,0,flcHeader.Xres,0,0,flcHeader.Xres,flcHeader.Yres,0,_
			0,0,0,1,1,0,1,1)
            glFlush
            #ENDIF
            #endif
            flip

        else
                'line (0,0)-(320,240),rgb(0,0,255),BF
                'line (0,40)-(320,240),rgb(0,255,50),BF
                if flcusetransparency then
                    if flcscreendepth>=24 then put (flcx,flcy),flcbuffer,alpha else put (flcx,flcy),flcbuffer,trans
                    'put (flcx,flcy),flcbuffer,trans
                else
                    put (flcx,flcy),flcbuffer,pset
                end if
'                screensync
'                flip

        end if
    end if
    end if
if delay>0 then
    do
        sleep 1,1
    loop until timer>flcplaytimer1
end if


if keyflag then
osgl_pollinput_keyboard()
osgl_pollinput()
if multikey(1) or multikey(28) or osgl_closewindow or osgl_button then
    flcloops=loops
    'if flcbuffer then ImageDestroy(flcbuffer) : flcBuffer=0
    if buffer then imagedestroy(buffer) : buffer=0
end if
end if
loop until buffer=0
next flcloops

#IFNDEF _osgl_softrender_
#IFNDEF __FB_DOS__
if myscreen.useopengl then
if flcTexture then
    glDeleteTextures (1,@flcTexture)
    flcTexture=0
end if
end if
#endif
#endif

CLOSE #flcFileNum
printdebug "FILE CLOSED: #"+str(flcfilenum)
flcFileNum=0
if buffer then
	ImageDestroy(buffer)
	buffer=0
end if
flcFrame=0

osgl_clearkeyboardbuffer()

end sub

function FLCloadsprite(filename as string,byval xtotal as integer,byval ytotal as integer) as any ptr
Screeninfo flcoglx,flcogly,flcscreendepth,,,,flcdriver
flcuseopengl=0:flcusetransparency=1
dim bigbuffer as any ptr=imagecreate(xtotal,ytotal,rgba(0,0,0,0),flcscreendepth)
dim xpos as integer
dim ypos as integer

FLCopen(filename)
do
    flcbuffer=FLCrendernextframe
    if flcFrame>1 then
    if flcbuffer<>0 then
        'if flcscreendepth>=24 then osgl_ChangeColor(flcbuffer,rgb(255,0,255),rgba(0,0,0,0))
        put bigbuffer,(xpos,ypos),flcbuffer,alpha,255
        'put bigbuffer,(xpos,ypos),flcbuffer,pset
        xpos+=flcHeader.Xres
        if xpos+flcHeader.Xres>xtotal-1 then xpos=0:ypos+=flcHeader.Yres
    end if
    end if
loop until flcbuffer=0
return bigbuffer
end function

sub osgl_loadspriteFLC(byref texturenumber as uinteger, filename as string, byref getlastframe as integer=0)
if osgl_fileexist(filename)=0 then exit sub
printdebug filename + " is " + osgl_filetype(filename)
if texturenumber=0 then texturenumber=osgl_freetexture
if texturearray(texturenumber).number>-1 then osgl_deletetexture(texturenumber)
osgl_inittexture(texturenumber)
texturearray(texturenumber).filename=filename
dim as uinteger xpos, ypos, xtotal, ytotal
'Screeninfo flcoglx,flcogly,flcscreendepth,,,,flcdriver
flcuseopengl=0:flcusetransparency=1
if texturearray(texturenumber).imagedata then
    imagedestroy texturearray(texturenumber).imagedata
    texturearray(texturenumber).imagedata=0
end if
texturearray(texturenumber).xslices=0
texturearray(texturenumber).yslices=1
texturearray(texturenumber).lastframe=-1
texturearray(texturenumber).currentframe=-1
texturearray(texturenumber).currenttext=""

FLCopen(filename)

getlastframe=flcHeader.flcframes-1
ytotal=flcHeader.Yres
xtotal=flcHeader.Xres*(flcHeader.flcframes+1)

dim as integer usemaxtexturesize=myscreen.maxtexturesize
if myscreen.texturescale2x then usemaxtexturesize=myscreen.maxtexturesize/2

if myscreen.useopengl or myscreen.maxtexturesize then
    while xtotal>usemaxtexturesize
        ytotal=ytotal*2
        xtotal=cint(xtotal/2)
    wend
    xtotal=makePOT(xtotal)
    ytotal=makePOT(ytotal)
end if

if ddfmode then
	xtotal=flcHeader.Xres*12
	'ytotal=flcHeader.Yres*(flcHeader.flcframes+1)/12
	ytotal=flcHeader.Yres*12
	texturearray(texturenumber).imagedata=imagecreate(xtotal,ytotal,rgba(255,0,255,255),32)
else
	texturearray(texturenumber).imagedata=imagecreate(xtotal,ytotal,rgba(0,0,0,0),32)
end if


do
    flcbuffer=FLCrendernextframe
    if flcFrame>1 then
    if flcbuffer<>0 then
        'if flcscreendepth>=24 then osgl_ChangeColor(flcbuffer,rgb(255,0,255),rgba(0,0,0,0))
        texturearray(texturenumber).lastframe+=1
        'put texturearray(texturenumber).imagedata,(xpos,ypos),flcbuffer,alpha,255
        put texturearray(texturenumber).imagedata,(xpos,ypos),flcbuffer,pset
        'put bigbuffer,(xpos,ypos),flcbuffer,pset
        xpos+=flcHeader.Xres
        if ypos=0 then texturearray(texturenumber).xslices+=1
        if xpos+flcHeader.Xres>xtotal then xpos=0:ypos+=flcHeader.Yres:texturearray(texturenumber).yslices+=1
    end if
    end if
loop until flcbuffer=0

'filter
'ImageBorderFilter texturearray(texturenumber).imagedata

texturearray(texturenumber).xsize=xtotal
texturearray(texturenumber).ysize=ytotal
texturearray(texturenumber).xslicesize=flcHeader.Xres
texturearray(texturenumber).yslicesize=flcHeader.Yres
texturearray(texturenumber).xslicesizefloat=flcHeader.Xres/xtotal
texturearray(texturenumber).yslicesizefloat=flcHeader.Yres/ytotal
texturearray(texturenumber).scaled=1

'printconsole "AAAAAAAAAAAAAAAAAAAAAA",xtotal,myscreen.maxtexturesize

if myscreen.texturescale2x then
if xtotal*2<=myscreen.maxtexturesize then
if ytotal*2<=myscreen.maxtexturesize then
	'ImageScale2X(texturearray(texturenumber).imagedata)
	'ImageEagle(texturearray(texturenumber).imagedata)
	ImageScale2XandEagle(texturearray(texturenumber).imagedata)
	texturearray(texturenumber).scaled=2
	texturearray(texturenumber).xsize=2*xtotal
	texturearray(texturenumber).ysize=2*ytotal
	texturearray(texturenumber).xslicesize=2*flcHeader.Xres
	texturearray(texturenumber).yslicesize=2*flcHeader.Xres
end if
end if
	if texturearray(texturenumber).scaled<>2 then
		printdebug "WARNING : Could not scale texture due to max. texture size!"
	end if
end if

if myscreen.useopengl then
    glUploadTexture(texturearray(texturenumber).number, texturearray(texturenumber).imagedata,,myscreen.useBGRA,myscreen.filter)
    if texturearray(texturenumber).imagedata then imagedestroy texturearray(texturenumber).imagedata : texturearray(texturenumber).imagedata=0
else
    texturearray(texturenumber).tmpimage=imagecreate(texturearray(texturenumber).xslicesize,texturearray(texturenumber).yslicesize)
end if

printdebug "FLC : ";filename;" tex = ";texturenumber;" : "+str(xtotal)+" x "+str(ytotal)+" : last frame = ";texturearray(texturenumber).lastframe;"."
end sub

sub osgl_loadspriteFLC2(byref texturenumber as uinteger, filename as string,byval xtotal as integer=-1,byval ytotal as integer=-1)
if texturenumber=0 then texturenumber=osgl_freetexture

'printconsole "aqui 1"

Screeninfo flcoglx,flcogly,flcscreendepth,,,,flcdriver
flcuseopengl=0:flcusetransparency=1
dim bigbuffer as any ptr=imagecreate(xtotal,ytotal,rgba(0,0,0,0))
dim as uinteger xpos, ypos, xslices, yslices
xslices=0:yslices=1
texturearray(texturenumber).lastframe=-1

'printconsole "aqui 2"
FLCopen(filename)

do
    flcbuffer=FLCrendernextframe
    if flcFrame>1 then
    if flcbuffer<>0 then
        'if flcscreendepth>=24 then osgl_ChangeColor(flcbuffer,rgb(255,0,255),rgba(0,0,0,0))
        texturearray(texturenumber).lastframe+=1
        put bigbuffer,(xpos,ypos),flcbuffer,alpha,255
        'put bigbuffer,(xpos,ypos),flcbuffer,pset
        xpos+=flcHeader.Xres
        if ypos=0 then xslices+=1
        if xpos+flcHeader.Xres>=xtotal then xpos=0:ypos+=flcHeader.Yres:yslices+=1
    end if
    end if
loop until flcbuffer=0
'printconsole "aqui 3"

if texturearray(texturenumber).number>-1 then osgl_deletetexture(texturenumber)
texturearray(texturenumber).xsize=xtotal
texturearray(texturenumber).ysize=ytotal
texturearray(texturenumber).xslices=xslices
texturearray(texturenumber).yslices=yslices
texturearray(texturenumber).xslicesize=flcHeader.Xres
texturearray(texturenumber).yslicesize=flcHeader.Yres
texturearray(texturenumber).xslicesizefloat=flcHeader.Xres/xtotal
texturearray(texturenumber).yslicesizefloat=flcHeader.Yres/ytotal
'printconsole "aqui 4"
if myscreen.useopengl then
    glUploadTexture(texturearray(texturenumber).number, bigbuffer,,myscreen.useBGRA,myscreen.filter)
'printconsole "aqui 5"
    'imagedestroy(bigbuffer)
'printconsole "aqui 6"
else
    texturearray(texturenumber).imagedata=bigbuffer
end if

printdebug "FLC : loaded ";filename;" as texture ";texturenumber;". Last frame is ";texturearray(texturenumber).lastframe;"."
end sub

dim shared as string openfilenamemt : openfilenamemt=""

sub osgl_openfilemt()
dim as string filename=openfilenamemt
dim as integer i=-1
if lcase(mid(filename,1,4))="www." then filename="http://"+filename
#IFDEF __FB_LINUX__
	i=exec2("xdg-open",filename)
	if i=-1 then i=exec2("gnome-open",filename)
	if i=-1 then i=exec2("kde-open",filename)
	if i=-1 then i=exec2("kfmclient",filename)
	if i=-1 then
		if lcase(mid(filename,1,7))="http://" then
			i=exec("firefox",filename)
			if i=-1 then i=exec2("google-chrome",filename)
			if i=-1 then i=exec2("konqueror",filename)
			if i=-1 then i=exec2("opera",filename)
		else
			i=exec("nautilus",filename)
			if i=-1 then i=exec2("konqueror",filename)
			if i=-1 then i=exec2("dolphin",filename)
		end if
	end if
#ENDIF
#IFDEF __FB_WIN32__
	ShellExecute(NULL,"open",filename,"","",SW_SHOWNORMAL)
#ENDIF
end sub

dim shared as any ptr osgl_openfilemt_thread
dim shared as any ptr osgl_openfilemt_ptr
sub osgl_openfile(filename as string="", backgroundmode as integer=0)
openfilenamemt=filename
if backgroundmode=0 then
	osgl_openfilemt()
else
	osgl_openfilemt_thread=threadcreate(osgl_openfilemt_ptr)
end if
end sub
osgl_openfilemt_ptr=@osgl_openfilemt


sub osgl_playvideo(filename as string)
if myscreen.windowxid=0 then printconsole "ERROR : playvideo : Could not obtain window XID" : exit sub
'shell "mplayer -wid "+str(myscreen.windowxid)+" -really-quiet /d/video/katrim.avi"
dim as string comando
#IFDEF __FB_WIN32__
	comando="mplayer.exe"
	if dir("./mplayer/mplayer.exe")<>"" then comando="./mplayer/mplayer.exe"
#ELSE
	if dir("./mplayer")<>"" then comando="./mplayer"
	if dir("./mplayer/mplayer")<>"" then comando="./mplayer/mplayer"
	if dir("/usr/bin/mplayer")<>"" then comando="/usr/bin/mplayer"
#ENDIF
printdebug "mplayer="+comando
if comando<>"" then
	comando+=" -wid "+str(myscreen.windowxid)+" -really-quiet "+filename
	dim as integer mypipe=freefile2()
	printdebug comando
	Open Pipe comando For output As #mypipe
	printdebug "FILE OPEN: #"+str(mypipe)
	do
	osgl_sync
	loop until multikey(1) or multikey(28) or multikey(57) or multikey(156)
	print #mypipe,CRLF
	close #mypipe
	printdebug "FILE CLOSED: #"+str(mypipe)
else
	osgl_openfile(filename)
end if
end sub



sub glUploadTexture(byref texture as integer, byval buffer as any ptr, byval mipmap as integer=1,byval useBGRA as integer=0, byval filter as integer=1)
#IFNDEF _osgl_softrender_
#IFNDEF __FB_DOS__

	myscreen.currenttexture=0

    dim as integer w, h

    dim pixdata as ubyte ptr
    imageinfo buffer,w,h,,,pixdata

    if isPOT(w)=0 or isPOT(h)=0 then
        w=makePOT(w)
        h=makePOT(h)
        imageresize(buffer,w,h)
        imageinfo buffer,w,h,,,pixdata
    end if

    if myscreen.useBGRA=0 then
        osgl_imageRGBA2BGRA(buffer)
    end if

    glEnable GL_Texture_2D
    if texture<0 then 'create texture
        glGenTextures 1, @texture
        glBindTexture GL_Texture_2D, texture
        if myscreen.useBGRA then
            glTexImage2D GL_Texture_2D, 0, myscreen.textureformat, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, pixdata
        else
            glTexImage2D GL_Texture_2D, 0, myscreen.textureformat, w, h, 0, myscreen.textureformat, GL_UNSIGNED_BYTE, pixdata
        end if
        glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_S, GL_CLAMP )
        glTexParameterf( GL_Texture_2D, GL_TEXTURE_WRAP_T, GL_CLAMP )
        if filter then
            glTexParameterf( GL_Texture_2D, GL_Texture_MAG_FILTER, GL_LINEAR )
            glTexParameterf( GL_Texture_2D, GL_Texture_MIN_FILTER, GL_LINEAR )
        else
            glTexParameterf( GL_Texture_2D, GL_Texture_MAG_FILTER, GL_NEAREST )
            glTexParameterf( GL_Texture_2D, GL_Texture_MIN_FILTER, GL_NEAREST )
        end if
		if mipmap then
			glTexEnvi( GL_Texture_ENV, GL_Texture_ENV_MODE, GL_MODULATE )
		end if
    else 'update texture
        glBindTexture GL_Texture_2D, texture
        if myscreen.useBGRA then
            glTexSubImage2D GL_TEXTURE_2D,0,0,0, w, h, GL_BGRA,GL_UNSIGNED_BYTE, pixdata
        else
            glTexSubImage2D GL_TEXTURE_2D,0,0,0, w, h, myscreen.textureformat, GL_UNSIGNED_BYTE, pixdata
        end if
    end if


#ENDIF
#endif
end sub


function osgl_squarecollision(byval x1a as integer,byval x2a as integer,byval y1a as integer,byval y2a as integer,byval x1b as integer,byval x2b as integer,byval y1b as integer,byval y2b as integer) as integer
if x2a<x1b  then return 0
if x1a>x2b  then return 0
if y2a<y1b  then return 0
if y1a>y2b  then return 0
return 1
end function


function osgl_collision(byval x1 as integer,byval y1 as integer,byval z1 as integer,byval rx1 as integer,byval ry1 as integer,byval x2 as integer,byval y2 as integer,byval z2 as integer,byval rx2 as integer,byval ry2 as integer,xscreen as integer=0,yscreen as integer=0,drawlines as integer=0) as integer
y1=-y1
y2=-y2
z1=-z1
z2=-z2
dim as integer x1a=x1-rx1,x1b=x1+rx1,   x2a=x2-rx2,x2b=x2+rx2,    y1a=y1-ry1,y1b=y1+ry1,   y2a=y2-ry2,y2b=y2+ry2
#IFNDEF _osgl_softrender_
if drawlines then
	glPushMatrix
    glDisable GL_TEXTURE_2D

    osgl_SetBlendMode(0)

    glTranslatef -xscreen,-yscreen,0
    glBegin GL_LINE_LOOP
        glColor4ub 255,0,0,255
        glVertex3f x1a,y1a, myscreen.eyez+z1
        glVertex3f x1b,y1a, myscreen.eyez+z1
        glVertex3f x1b,y1b, myscreen.eyez+z1
          glVertex3f x1a,y1b, myscreen.eyez+z1
    glEnd
    glBegin GL_LINE_LOOP
        glColor4ub 0,0,255,255
        glVertex3f x2a,y2a, myscreen.eyez+z2
        glVertex3f x2b,y2a, myscreen.eyez+z2
        glVertex3f x2b,y2b, myscreen.eyez+z2
          glVertex3f x2a,y2b, myscreen.eyez+z2
    glEnd
    glPopMatrix
end if
#ENDIF
if x1b<x2a  then return 0
if x1a>x2b  then return 0
if y1b<y2a  then return 0
if y1a>y2b  then return 0
return 1
end function


sub osgl_drawcollision(byval x1 as integer,byval y1 as integer,byval rx1 as integer,byval ry1 as integer,byval x2 as integer,byval y2 as integer,byval rx2 as integer,byval ry2 as integer,byval xscreen as integer,byval yscreen as integer)
y1=-y1
y2=-y2
dim as integer x1a=x1-rx1,x1b=x1+rx1,   x2a=x2-rx2,x2b=x2+rx2,    y1a=y1-ry1,y1b=y1+ry1,   y2a=y2-ry2,y2b=y2+ry2
#IFNDEF _osgl_softrender_
    glBegin GL_LINE_LOOP
        glColor4ub 255,0,0,255
        glVertex2f x1a,y1a-yscreen
        glVertex2f x1b,y1a-yscreen
        glVertex2f x1b,y1b-yscreen
          glVertex2f x1a,y1a-yscreen
    glEnd
    glBegin GL_LINE_LOOP
        glColor4ub 0,0,255,255
        glVertex2f x2a,y2a-yscreen
        glVertex2f x2b,y2a-yscreen
        glVertex2f x2b,y2b-yscreen
          glVertex2f x2a,y2a-yscreen
    glEnd
#ENDIF
end sub


sub osgl_ChangeColor2(byval buffer as any ptr, byval oldcolor as uinteger, byval newcolor as uinteger)
#if __FB_LANG__="fb"

    dim as integer w, h, x, y, col,i,pit
    dim as FB.PUT_Header ptr Header = buffer

    if Header->type = FB.PUT_Header_NEW then
        w = Header->width
        h = Header->height
        pit = Header->pitch
    else
        w = Header->old.width
        h = Header->old.height
        pit = Header->pitch
    end if

    dim oldr as integer=rgbar(oldcolor)
    dim oldg as integer=rgbag(oldcolor)
    dim oldb as integer=rgbab(oldcolor)
    dim olda as integer=rgbaa(oldcolor)

    dim newr as integer=rgbar(newcolor)
    dim newg as integer=rgbag(newcolor)
    dim newb as integer=rgbab(newcolor)
    dim newa as integer=rgbaa(newcolor)

    'printconsole "old r";oldr;"g";oldg;"b";oldb;"a";olda
    'printconsole "new r";newr;"g";newg;"b";newb;"a";newa

    'Dim As ubyte Ptr pByte = buffer
    Dim As uByte Ptr pByte
    ImageInfo buffer,,,,,pByte
    'Dim As FBImage Ptr pByte = buffer
    Dim As Integer TextSize = (w * h * 4)+pit
    For i As Integer = 0 To TextSize-1 step 4
    'printconsole "r";*(pByte+i);"g";*(pByte+i+1);"b";*(pByte+i+2);"a";*(pByte+i+3)
    if *(pByte+i)=oldr then
    if *(pByte+i+1)=oldg then
    if *(pByte+i+2)=oldb then
    if *(pByte+i+3)=olda then
        *(pByte+i)=newr
        *(pByte+i+1)=newg
        *(pByte+i+2)=newb
        *(pByte+i+3)=newa
    end if
    end if
    end if
    end if
        'Swap *(pByte+i), *(pByte+i+2)
    'if peek(uinteger, buffer+i)=oldcolor then poke uinteger,(buffer+i),newcolor
    Next i

#endif
end sub


sub osgl_ChangeColor(byval buffer as any ptr, byval oldcolor as uinteger, byval newcolor as uinteger)

    dim as integer w,h
    ImageInfo buffer,w,h

    For j as integer = 0 To h
    For i as integer = 0 To w
        if point (i,j,buffer)=oldcolor then pset buffer,(i,j),newcolor
    Next i
    Next j

end sub


Function osgl_ScreenSupported( _
    Byval ScreenWidth As Integer, _
    Byval ScreenHeight As Integer, _
    Byval Colour As uInteger) As Integer

Dim As Integer mode, w, h
    mode = ScreenList(Colour)
    While (mode)
        w = Hiword(mode)
        h = Loword(mode)
        If w = ScreenWidth And h = ScreenHeight Then
            Function = -1
            Exit Function
        End If
        mode = ScreenList
    Wend

End Function


Function osgl_LoadString(byval filename As String) As String

Dim h As Integer=freefile2()

  Dim txt As String
  if Open(filename For Binary Access Read As #h) then
    printconsole filename+" : could not open file"
    return ""
  else
    If LOF(h) > 0 Then
        txt = String(LOF(h),0)
        Get #h,,txt
    else
        txt=""
    End If
    Close #h
  end if
  'txt=txt+CRLF
  return txt
End Function


sub osgl_SaveString(byval stringbuffer as string,byval filename As String)

Dim h As Integer=freefile2()

'  if Open(filename For Binary Access write As #h) then
  if Open(filename For binary access write As #h) then
    printconsole filename+" : could not write file"
else
    put #h,,stringbuffer,len(stringbuffer)
    Close #h
end if
'  if BSave( filename, strptr(stringbuffer), len(stringbuffer) ) then printconsole filename+" : could not write file"
End sub


Function INIGetString(byval stringbuffer as string,byval section as string="CONFIG",byval variable as string,byval vardefault as string="default") as string
if stringbuffer="" then
	printdebug "INIGetString : buffer is empty!"
	function=vardefault: exit function
end if
dim varlen as long=len(variable)
dim as string lstringbuffer=lcase(stringbuffer)
'first = InStr( [ start, ] str, [ Any ] substring )
dim sectionpos as long=instr(lstringbuffer,"["+lcase(section)+"]")
dim endsectionpos as long=instr(sectionpos+len(section)+3,stringbuffer,"[")
if endsectionpos=0 then endsectionpos=len(stringbuffer)
'print sectionpos, endsectionpos
if sectionpos=0 then function=vardefault : exit function
dim variablepos as long=instr(sectionpos,lstringbuffer,chr(10)+lcase(variable)+"=")
'não achou var
if variablepos=0 or variablepos>endsectionpos then function=vardefault: exit function

'dim varendpos as long=instr(variablepos+varlen+2,stringbuffer,any CRLF+chr(0)+" ")
dim varendpos as long=instr(variablepos+varlen+2,stringbuffer,any CRLF+chr(0))
if varendpos=0 then varendpos=len(stringbuffer)+1
'result = Mid( str, start [, n ] )
dim value as string=trim(mid(stringbuffer,variablepos+varlen+2,varendpos-variablepos-varlen-2))
if mid(value,1,1)=chr(34) then value=mid(value,2,len(value)-2)
if value="" then function=vardefault: exit function
function=value
end function


sub INISetString(byref stringbuffer as string,byval section as string="CONFIG",byval variable as string,byval value as string="default")
dim varlen as long=len(variable)
dim vallen as long=len(value)
dim as string lstringbuffer=lcase(stringbuffer)
'first = InStr( [ start, ] str, [ Any ] substring )
dim sectionpos as long=instr(lstringbuffer,"["+lcase(section)+"]")
if sectionpos=0 then
    stringbuffer=rtrim(stringbuffer,any CRLF)+CRLF+CRLF
    sectionpos=len(stringbuffer)+1
    stringbuffer=stringbuffer+"["+section+"]"+CRLF
end if
dim sectionend as long=instr(sectionpos+len(section)+2,lstringbuffer,"[")
if sectionend=0 then sectionend=len(lstringbuffer)
dim variablepos as long=instr(sectionpos+len(section)+2,lstringbuffer,lcase(variable)+"=")
'result = Mid( str, start [, n ] )
if variablepos=0 or variablepos>sectionend then
    stringbuffer=rtrim(mid(stringbuffer,1,sectionpos+len(section)+2),any CRLF)+CRLF+variable+"="+value+CRLF+ltrim(mid(stringbuffer,sectionpos+len(section)+3,len(stringbuffer)-sectionpos-len(section)+1),any CRLF)
else
    'dim varendpos as long=instr(variablepos+varlen+1,stringbuffer,any CRLF+chr(0)+" ")
    dim varendpos as long=instr(variablepos+varlen+1,stringbuffer,any CRLF+chr(0))
    stringbuffer=rtrim(mid(stringbuffer,1,variablepos-1),any CRLF)+CRLF+variable+"="+value+CRLF+ltrim(mid(stringbuffer,varendpos,len(stringbuffer)-varendpos+1),any CRLF)
end if
end sub


dim shared as string sys_inifile, sys_inifilecontents,emptystring
emptystring=" "
dim shared emptyzstring as zstring ptr
emptyzstring=strptr(emptystring)

function osgl_inireads cdecl alias "osgl_inireads" (zinifile as zstring ptr=emptyzstring, zsection as zstring ptr=emptyzstring, zkey as zstring ptr=emptyzstring, zdefaultvalue as zstring ptr=emptyzstring) as zstring ptr export
'INI READ$(inifile$,"PLAYER"+str$(player+1),inputshortname$(i),"0")
dim as string inifile=*zinifile
static as string answer
static zanswer as zstring ptr
if inifile<>sys_inifile then
	sys_inifile=inifile
	sys_inifilecontents=osgl_LoadString(sys_inifile)
end if
answer=INIGetString(sys_inifilecontents,*zsection,*zkey,*zdefaultvalue)
if answer<>"" then zanswer=strptr(answer) else zanswer=emptyzstring
function=zanswer
end function


function osgl_iniread cdecl alias "osgl_iniread" (zinifile as zstring ptr=emptyzstring, zsection as zstring ptr=emptyzstring, zkey as zstring ptr=emptyzstring, defaultvalue as integer=0) as integer export
dim as string inifile=*zinifile
static as string answer
dim as integer intanswer
dim sdefaultvalue as string=str(defaultvalue)
dim zdefaultvalue as zstring ptr=strptr(sdefaultvalue)
if inifile<>sys_inifile then
	sys_inifile=inifile
	sys_inifilecontents=osgl_LoadString(sys_inifile)
end if
answer=INIGetString(sys_inifilecontents,*zsection,*zkey,*zdefaultvalue)
intanswer=val(answer)
function=intanswer
end function


sub osgl_iniwrite cdecl alias "osgl_iniwrite" (zinifile as zstring ptr=emptyzstring, zsection as zstring ptr=emptyzstring, zkey as zstring ptr=emptyzstring, value as zstring ptr=emptyzstring) export
'INI WRITE inifile$,"PLAYER"+str$(player+1),inputshortname$(i),str$(inputarray(player,i))
dim as string inifile=*zinifile
if inifile<>sys_inifile then
	sys_inifile=inifile
	sys_inifilecontents=osgl_LoadString(sys_inifile)
end if
INISetString(sys_inifilecontents,*zsection,*zkey,*value)
osgl_SaveString(sys_inifilecontents,inifile)
end sub


#define make_u32(n) ((((n) and &h000000ff) shl 24) _
                  or (((n) and &h0000ff00) shl 8) _
                  or (((n) and &h00ff0000) shr 8) _
                  or (((n) and &hff000000) shr 24))

#define put_u32(p, n) *cptr( uinteger ptr, p ) = make_u32(n)

#define osgl_savepng png_save


function LoadBuffer(byval filename as string) as any ptr
dim buffer as ubyte ptr

Dim h As Integer=freefile2()

  if Open(filename For Binary Access Read As #h) then
	printdebug "FILE OPEN: #"+str(h)
    printconsole filename+" : could not open file"
    return 0
  else
    If LOF(h) > 0 Then
        buffer = allocate(LOF(h)*sizeof(ubyte))
        Get #h,,*buffer
    else
        buffer=0
    End If
    Close #h
	printdebug "FILE CLOSED: #"+str(h)
  end if

return buffer
end function


sub gethomedir()
#if defined (__FB_LINUX__)
    returnhomedir=environ("HOME")+"/"
#endif
#if defined (__FB_WIN32__)
    returnhomedir=Environ ("USERPROFILE")
    if instr(returnhomedir,"\") then returnhomedir+="\" else returnhomedir+="/"
#endif
#if defined (__FB_DOS__)
    returnhomedir=exepath+"\"
#endif
if returnhomedir="" then returnhomedir=".\"
end sub


function homedir() as string
    if returnhomedir="" then gethomedir()
    return returnhomedir
end function


function osgl_filefullnamepart(filename as string) as string
dim as string appcommand=filename
dim as string returnappname2
dim barra as string*1 : barra="/"
dim i as integer=1
do
    i+=1
    if StringFromList(appcommand,i,barra)="" then
        returnappname2=StringFromList(appcommand,i-1,barra)
    end if
loop until returnappname2<>""
#if defined (__FB_WIN32__) or defined (__FB_DOS__)
    i=1
    barra="\"
    appcommand=returnappname2
    returnappname2=""
    do
        i+=1
        if StringFromList(appcommand,i,barra)="" then
            returnappname2=StringFromList(appcommand,i-1,barra)
        end if
    loop until returnappname2<>""
#endif
if mid(returnappname2,1,2)="./" or mid(returnappname2,1,2)=".\" then returnappname2=right(returnappname2,len(returnappname2)-2)
function=returnappname2
end function


function osgl_filepathpart(filename as string) as string
dim as string returnappname2
returnappname2=osgl_filefullnamepart(filename)
function=left(filename,len(filename)-len(returnappname2))
end function


function osgl_filenamepart(filename as string) as string
function=StringFromList(osgl_filefullnamepart(filename),1,".")
end function


function osgl_getfileextensionpart(filename as string) as string
function=StringFromList(osgl_filefullnamepart(filename),2,".")
end function


sub getappname()
dim appcommand as string=command(0)
printconsole "Init : Run Command : command(0) = "+appcommand
returnappname=osgl_filenamepart(appcommand)
if returnappname="" then
    printconsole "Init : ERROR!!! Could not get appname!"
else
    printconsole "Init : Application Name : appname = "+returnappname
end if
end sub


function appname() as string
	#ifdef _osgl_forceappname_
		function=_osgl_forceappname_
		exit function
	#endif
    if returnappname="" then getappname()
    function=returnappname
end function


Function arctan2(dy as single,dx as single) as single

' angle constants
  Const ANG_RANGE=360
  Const ANG_PI2  =2*PI/ANG_RANGE
  Const ANG_DIV2 =  ANG_RANGE/2
  Const ANG_DIV4 =  ANG_RANGE/4
  Const ANG_DIV34=3*ANG_DIV4

    Dim as single angle

    If dx Then
      angle=Atn(dy/dx)*ANG_DIV2/PI
      If (dx<0) Then angle+=ANG_DIV2
    Else
      If (dy>0) Then angle=ANG_DIV4 Else angle=ANG_DIV34
    End If

    If (angle<0) Then angle+=ANG_RANGE

    Return angle

End Function


'sub osgl_end() Destructor
sub osgl_end()
printconsole "System : osgl_end"
if myscreen.suspendscreensaver then osgl_screensaver 1
osgl_clear
osgl_ended=1

if sound.sfx_on or sound.music_on then
    printconsole "Audio : Closing . . . ";
    Mix_CloseAudio()
    sound.started=0
    printconsole "OK!"
end if

if sound.useSDL=1 then SDL_Quit() : sound.useSDL=0
if libsdl then printconsole "SDL : unloading SDL . . ."; : dylibfree libsdl : libsdl=0 : printconsole " OK!"
if libsdlmixer then printconsole "SDL : unloading SDL_mixer . . ."; : dylibfree libsdlmixer : libsdlmixer=0 : printconsole " OK!"

#ifndef holtek_hack
	if libjoyrumble then printconsole "Input : unloading libjoyrumble . . ."; : dylibfree libjoyrumble : libjoyrumble=0 : printconsole " OK!"
#endif

'end sub


'sub osgl_destructor()  Destructor
'sub osgl_destructor()
'if osgl_ended=0 then osgl_end
'ThreadWait(inputthread)

printdebug "Memory : ini="+str(osgl_freemembegin)
printdebug "Memory : end="+str(fre)

printconsole "Screen : Total Frames Rendered = "+str(myscreen.framesdrawn)
printconsole "Screen : Average FPS = "+str(cint(myscreen.framesdrawn/(timer-osgl_begintimer)))
#ifndef _osgl_noscreen_
if myscreen.fullscreen then
    printconsole "Screen : Restoring "+str(myscreen.originalx)+"x"+str(myscreen.originaly)+" desktop . . . ";
	#ifdef __FB_WIN32__
		screencontrol 103,"gdi"
	#endif
    screenres myscreen.originalx,myscreen.originaly,32,,&h01
    'cls
    printconsole "OK!"
end if
#endif

printconsole "Bye bye!"

if consoleon then
	close CONSOLEHANDLE
	consoleon=0
	screen 0
	print ""
	print "Leaving... Bye!"
	print ""
end if
osgl_quitprogram=1
close

if osgl_openfilemt_thread then threadwait(osgl_openfilemt_thread)

end

end sub


function osgl_canwrite(writedir as string) as integer
dim as string directory=writedir
if mid(directory,len(directory),1)="/" or mid(directory,len(directory),1)="\" then directory=left(directory,len(directory)-1)
dim As UInteger out_attr
dim as integer result=(dir(directory,&h01 or &h02 or &h04 or &h10 or &h20,out_attr)="")
if (out_attr and &h01) or result then function=0 else function=1
end function



#ifdef __FB_WIN32__

#include once "windows.bi"
#include once "win\shlobj.bi"

dim shared as string wingetpath : wingetpath=string(MAX_PATH-1,0)

function win32_folder_appdata as string
wingetpath=string(MAX_PATH-1,0)
dim as HRESULT hres
hres=SHGetFolderPath(_
        NULL,_
        CSIDL_APPDATA or CSIDL_FLAG_CREATE,_
        NULL,_
        SHGFP_TYPE_CURRENT,_
        strptr(wingetpath))
	function=trim(wingetpath)
printdebug "Win32 Appdata Folder = "+wingetpath
end function

function win32_folder_desktop as string
wingetpath=string(MAX_PATH-1,0)
dim as HRESULT hres
hres=SHGetFolderPath(_
        NULL,_
        CSIDL_DESKTOP or CSIDL_FLAG_CREATE,_
        NULL,_
        SHGFP_TYPE_CURRENT,_
        strptr(wingetpath))
	function=trim(wingetpath)
'        CSIDL_DESKTOPDIRECTORY or CSIDL_FLAG_CREATE,_
printdebug "Win32 Desktop Folder = "+wingetpath
end function

function win32_folder_programs as string
wingetpath=string(MAX_PATH-1,0)
dim as HRESULT hres
hres=SHGetFolderPath(_
        NULL,_
        CSIDL_PROGRAMS or CSIDL_FLAG_CREATE,_
        NULL,_
        SHGFP_TYPE_CURRENT,_
        strptr(wingetpath))
	function=trim(wingetpath)
printdebug "Win32 Programs Folder = "+wingetpath
end function

function win32_folder_games as string
dim as string prg=win32_folder_programs
if dir(prg+"\Games",&h01 or &h02 or &h04 or &h10 or &h20)="" then mkdir prg+"\Games"
prg=prg+"\Games"
function=prg
printdebug "Win32 Games Folder = "+prg
end function

#endif



sub osgl_CreateShortcut()
printconsole "Createshortcut : Creating shortcuts..."
getappname

dim as string appfullname=appname
#ifdef _osgl_appfullname_
 appfullname=_osgl_appfullname_
#endif

dim shortcutcontents as string
#ifdef __FB_LINUX__
    printconsole "Createshortcut : OS = Linux"
    'Criar atalhos no Linux:
    '{homedir}/.local/share/applications    (menu)
    '{homedir}/Desktop

    shortcutcontents=    "[Desktop Entry]"+CRLF+_
                    "Name="+appfullname+CRLF+_
                    "GenericName="+appfullname+CRLF+_
                    "Description="+appfullname+CRLF+_
                    "Comment=Game"+CRLF+_
                    "Path="+exepath+CRLF+_
                    "Exec="+exepath+"/"+returnappname+CRLF+_
                    "Icon="+exepath+"/"+appname+".png"+CRLF+_
                    "Terminal=false"+CRLF+_
                    "Type=Application"+CRLF+_
                    "Categories=Game;"

                    'Categories=Application;System;
                    'Categories=Game;ArcadeGame;
                    'Categories=3DGraphics;Game;ActionGame;
                    'Categories=Qt;KDE;Game;StrategyGame;
                    'Categories=Game;RolePlaying;

'ActionGame	An action game	Game
'AdventureGame	Adventure style game	Game
'ArcadeGame	Arcade style game	Game
'BoardGame	A board game	Game
'BlocksGame	Falling blocks game	Game
'CardGame	A card game	Game
'KidsGame	A game for kids	Game
'LogicGame	Logic games like puzzles, etc	Game
'RolePlaying	A role playing game	Game
'Simulation	A simulation game	Game
'SportsGame	A sports game	Game
'StrategyGame	A strategy game

    #ifdef _osgl_gamestyle_action_
        shortcutcontents=shortcutcontents+"ActionGame;Action;"
    #endif
    #ifdef _osgl_gamestyle_adventure_
        shortcutcontents=shortcutcontents+"AdventureGame;Adventure;"
    #endif
    #ifdef _osgl_gamestyle_arcade_
        shortcutcontents=shortcutcontents+"ArcadeGame;Arcade;"
    #endif
    #ifdef _osgl_gamestyle_board_
        shortcutcontents=shortcutcontents+"BoardGame;Board;"
    #endif
    #ifdef _osgl_gamestyle_blocks_
        shortcutcontents=shortcutcontents+"BlocksGame;Blocks;"
    #endif
    #ifdef _osgl_gamestyle_card_
        shortcutcontents=shortcutcontents+"CardGame;Card;"
    #endif
    #ifdef _osgl_gamestyle_kids_
        shortcutcontents=shortcutcontents+"KidsGame;Kids;"
    #endif
    #ifdef _osgl_gamestyle_logic_
        shortcutcontents=shortcutcontents+"LogicGame;Logic;"
    #endif
    #ifdef _osgl_gamestyle_rpg_
        shortcutcontents=shortcutcontents+"RolePlaying;RolePlayingGame;RPG;"
    #endif
    #ifdef _osgl_gamestyle_simulation_
        shortcutcontents=shortcutcontents+"SimulationGame;Simulation;"
    #endif
    #ifdef _osgl_gamestyle_sport_
        shortcutcontents=shortcutcontents+"SportsGame;Sports;"
    #endif
    #ifdef _osgl_gamestyle_strategy_
        shortcutcontents=shortcutcontents+"StrategyGame;Strategy;"
    #endif

    shortcutcontents=shortcutcontents+CRLF

    printconsole "Createshortcut : saving in `"+homedir+".local/share/applications/`"
    if dir(homedir+".local/share/applications",&h10)<>"" then osgl_SaveString shortcutcontents,homedir+".local/share/applications/"+appname+".desktop" else printconsole "Createshortcut : ERROR - could not save in "+homedir+".local/share/applications/"
    printconsole "Createshortcut : saving in `"+homedir+"Desktop/`"
    if dir(homedir+"Desktop",&h10)<>"" then osgl_SaveString shortcutcontents,homedir+"Desktop/"+appname+".desktop" else printconsole "Createshortcut : ERROR - could not save in ~/Desktop/"
    printconsole "Createshortcut : Done!"
    exit sub
#endif

#ifdef __FB_WIN32__
    printconsole "Createshortcut : OS = windows"

    shortcutcontents=    "[InternetShortcut]"+CRLF+_
    "URL=file:///"+exepath+"\"+returnappname+".exe"+CRLF+_
    "IconIndex=0"+CRLF+_
    "IconFile="+exepath+"\"+appname+".exe"+CRLF

    'environ("ALLUSERSPROFILE")+"/Desktop"
    '[InternetShortcut]
	'URL=file:///l:/cleber/2dgl/iceroyds.exe
	'IconIndex=0
	'IconFile=l:\cleber\2dgl\iceroyds.exe

    'printconsole "ERROR : Function is not supported in this platform!!!"
    'exit sub
    'Criar atalhos no windows:
    '{homedir}\Desktop\
    '{homedir}\Start Menu\Games\ (verificar se existe)
    '{homedir}\Menu Iniciar\Jogos\ (verificar se existe)

'vista / 7
	' menu :   APPDATA\Microsoft\Windows\Start Menu\Programs\Games\
	'
#ifdef oldmethod
	'all users
	printconsole "Createshortcut : saving in `"+environ("ALLUSERSPROFILE")+"\Desktop\`"
		osgl_SaveString shortcutcontents,environ("ALLUSERSPROFILE")+"\Desktop\"+appfullname+".url"
	printconsole "Createshortcut : saving in `"+environ("ALLUSERSPROFILE")+"\"+chr(&hc1)+"rea de trabalho\`"
		osgl_SaveString shortcutcontents,environ("ALLUSERSPROFILE")+"\"+chr(&hc1)+"rea de trabalho\"+appfullname+".url"
	printconsole "Createshortcut : saving in `"+environ("ALLUSERSPROFILE")+"\Start Menu\Games\`"
		osgl_SaveString shortcutcontents,environ("ALLUSERSPROFILE")+"\Start Menu\Games\"+appfullname+".url"
	printconsole "Createshortcut : saving in `"+environ("ALLUSERSPROFILE")+"\Menu Iniciar\Jogos\`"
		osgl_SaveString shortcutcontents,environ("ALLUSERSPROFILE")+"\Menu Iniciar\Jogos\"+appfullname+".url"
	'current user
	printconsole "Createshortcut : saving in `"+environ("USERPROFILE")+"\Desktop\`"
		osgl_SaveString shortcutcontents,environ("USERPROFILE")+"\Desktop\"+appfullname+".url"
	printconsole "Createshortcut : saving in `"+environ("USERPROFILE")+"\"+chr(&hc1)+"rea de trabalho\`"
		osgl_SaveString shortcutcontents,environ("USERPROFILE")+"\"+chr(&hc1)+"rea de trabalho\"+appfullname+".url"
	printconsole "Createshortcut : saving in `"+environ("USERPROFILE")+"\Start Menu\Games\`"
		osgl_SaveString shortcutcontents,environ("USERPROFILE")+"\Start Menu\Games\"+appfullname+".url"
	printconsole "Createshortcut : saving in `"+environ("USERPROFILE")+"\Menu Iniciar\Jogos\`"
		osgl_SaveString shortcutcontents,environ("USERPROFILE")+"\Menu Iniciar\Jogos\"+appfullname+".url"
	'vista / 7 menu
	printconsole "Createshortcut : saving in `"+environ("PROGRAMDATA")+"\Microsoft\Windows\Start Menu\Programs\Games\`"
		osgl_SaveString shortcutcontents,environ("PROGRAMDATA")+"\Microsoft\Windows\Start Menu\Programs\Games\"+appfullname+".url"
	printconsole "Createshortcut : saving in `"+environ("APPDATA")+"\Microsoft\Windows\Start Menu\Programs\Games\`"
		osgl_SaveString shortcutcontents,environ("APPDATA")+"\Microsoft\Windows\Start Menu\Programs\Games\"+appfullname+".url"
#endif

	dim as string tmp=win32_folder_games
	printconsole "Createshortcut : saving in Games menu : "+tmp
	osgl_SaveString shortcutcontents,tmp+"\"+appfullname+".url"

	tmp=win32_folder_desktop
	printconsole "Createshortcut : saving in Desktop : "+tmp
	osgl_SaveString shortcutcontents,tmp+"\"+appfullname+".url"

	printconsole "Createshortcut : Done!"
	exit sub
#endif

#ifdef __FB_DOS__
    printconsole "Createshortcut : OS = DOS"
    printconsole "ERROR : Function is not supported in this platform!!!"
    exit sub
#endif

printconsole "Createshortcut : OS = ?"
printconsole "I don't know how to create a shortcut for this platform."

end sub


function LoadBMP (byval filename as string) as any ptr
if osgl_fileexist(filename)=0 then function=0 : exit function
        Dim As Uinteger handle
        Dim As Integer ff=freefile2()
        Dim As Integer W, H
        Open filename For Binary As #ff
		printdebug "FILE OPEN: #"+str(ff)
        Get #ff, 19, W
        Get #ff, 23, H
        Close #ff
		printdebug "FILE CLOSED: #"+str(ff)
        Dim As Any Ptr buffer = ImageCreate(w,h)
        Bload filename, buffer
    return buffer
end function

'windows registry registro crap
#ifdef __FB_WIN32__rem
'#ifdef REMSTART

'#define HKEY_CLASSES_ROOT  &H80000000
'#define HKEY_CURRENT_CONFIG  &H80000005
'#define HKEY_CURRENT_USER  &H80000001
'#define HKEY_DYN_DATA  &H80000006
'#define HKEY_LOCAL_MACHINE  &H80000002
'#define HKEY_PERFORMANCE_DATA  &H80000004
'#define HKEY_USERS  &H80000003

Dim Shared RegVal As Zstring * 1024

'Dim Shared root As hkey

'RegistryGet(HKEY_CLASSES_ROOT,"http\shell\open\command", "", @RegVal)
Sub RegistryGet(root As HKEY=HKEY_LOCAL_MACHINE, sub_ As Zstring Ptr, name_ As Zstring Ptr, out_ As Zstring Ptr)

  Dim hKey_ As HKEY
  Dim As Long rc,KeyValType
  Dim KeyData As Long
    If RegOpenKeyEx(root, sub_, 0, KEY_READ, @hKey_) = ERROR_SUCCESS Then
        Dim l As DWORD = 512
        Dim t As DWORD
'        If RegQueryValueEx(hKey_, name_, NULL, @t, out_, @l) <> ERROR_SUCCESS OR (t <> REG_SZ AND t <> REG_EXPAND_SZ) Then Exit Sub
'        out_[512 - 1] = 0
        If RegQueryValueEx(hKey_, name_, NULL, @t, out_, @l) <> ERROR_SUCCESS Then Exit Sub
                If t = REG_SZ Then
                        out_[512 - 1] = 0
                End If
                If t = REG_DWORD Then
            rc = RegQueryValueEx(hKey_, name_, NULL, @t, out_, @l)
'            KeyData=out_
'            print len(keydata)
'            If Asc(Mid(KeyData, Len(KeyData), 1)) = 0 Then
'                KeyData = Left(KeyData, Len(KeyData) - 1)
'            Else
'                KeyData = Left(KeyData, Len(KeyData))
'            End If
            'print *name_
            RegVal=Str$(Asc(*out_))
        End If
        RegCloseKey(hKey_)
    End If
End Sub


'RegistrySet(HKEY_LOCAL_MACHINE,"SOFTWARE\Yetifoot\Test", "HELLO", "Blah Blah")
Sub RegistrySet(root As HKEY=HKEY_LOCAL_MACHINE, sub_ As Zstring Ptr, name_ As Zstring Ptr, in_ As Zstring Ptr)
  Dim hKey_ As HKEY
    RegCreateKeyEx(root,sub_,0,0,REG_OPTION_NON_VOLATILE,KEY_SET_VALUE,NULL,@hKey_,0)
    RegSetValueEx(hKey_,name_,0,REG_SZ,in_,Len(*in_)+1)
    RegCloseKey(hKey_)
End Sub


declare function hStripFilePath( byval filename as zstring ptr ) as string
declare function hStripFileExt( byval filename as zstring ptr ) as string

'declare function osgl_CreateShortcut( byval TargetName as zstring ptr, _
'                                          byval LinkName as zstring ptr ) as integer


'' main
    'randomize timer

    '' create a desktop shortcut to itself
    'osgl_CreateShortcut( ExePath( ) & "\" & hStripFileExt( __FILE__ ) & ".exe", _
     '                      "FB Created Link #" & cint( rnd * 100 ) & ".lnk" )



'':::::
function osgl_CreateShortcut( byval TargetName as zstring ptr, _
                               byval LinkName as zstring ptr ) as integer
    dim as IShellLink ptr ISLink
    dim as IPersistFile ptr IPFile
    dim as LPITEMIDLIST PIDL
    dim as zstring * MAX_PATH InFolder

    function = FALSE

    ''
    CoInitialize( NULL )

    ''
    SHGetSpecialFolderLocation( 0, CSIDL_DESKTOPDIRECTORY, @PIDL )
    SHGetPathFromIDList( PIDL, InFolder )

    ''
    CoCreateInstance( @CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, @IID_IShellLink, @ISLink )

    IShellLinkA_SetPath( ISLink, TargetName )
    IShellLinkA_SetWorkingDirectory( ISLink, hStripFilePath( TargetName ) )

    ''
    IShellLinkA_QueryInterface( ISLink, @IID_IPersistFile, @IPFile )

    IPersistFile_Save( IPFile, InFolder + "\" + *LinkName, 0 )

    ''
    IPersistFile_Release( IPFile )

    IShellLinkA_Release( ISLink )

    CoUninitialize( )

    function = TRUE

end function


'':::::
function hStripFilePath( byval filename as zstring ptr ) as string static
    dim as integer lp, p

    lp = 0
    do
        p = instr( lp+1, *filename, "\" )
        if p=0 then
            exit do
        end if
        lp = p
    loop

    if( lp > 0 ) then
        function = mid( *filename, lp+1 )
    else
        function = *filename
    end if

end function

'':::::
function hStripFileExt( byval filename as zstring ptr ) as string static
    dim p as integer, lp as integer

    lp = 0
    do
        p = instr( lp+1, *filename, "." )
        if( p = 0 ) then
            exit do
        end if
        lp = p
    loop

    if( lp > 0 ) then
        function = left( *filename, lp-1 )
    else
        function = *filename
    end if

end function

#ENDIF


function osgl_FreeTexture as integer
'if texturenumber=0 then texturenumber=osgl_freetexture
for i as integer=1 to maxtexture
if myscreen.useopengl then
    if texturearray(i).number<0 then
        printdebug "Texture : texture "+str(i)+" is free"
        function=i : exit function
    end if
else
    if texturearray(i).imagedata=0 then
        printdebug "Texture : texture "+str(i)+" is free"
        function=i : exit function
    end if
end if
next i
end function

dim shared as single _osgl_menuscale=1.0
dim shared as integer _osgl_textboxoffset=0

sub osgl_drawmouse(byval cursortype as integer=0, byval texture as integer=0)
if myscreen.mouseclip then exit sub
if myscreen.mouseinactive>=_osgl_mousetimeout then myscreen.mouseclip=1: exit sub
dim as integer x=myscreen.mousex
dim as integer y=myscreen.mousey

dim as integer ma=15*_osgl_mousetimeout*(1.0-(myscreen.mouseinactive/_osgl_mousetimeout))
osgl_range(ma,0,210)

if myscreen.mousetouchscreen=0 then

osgl_SetBlendMode 1
glPushMatrix
glDisable GL_TEXTURE_2D

dim w as integer=24*_osgl_menuscale
dim h as integer=24*_osgl_menuscale

gltranslatef x,y,0
glrotatef 35,0,0,1

'gltranslatef 2,-8,0
'glscalef 1.4,1.4,1

   'shadow
    glBegin GL_TRIANGLE_STRIP
        glColor4ub 0,0,0,32
        glVertex3f -w/2,-h, myscreen.eyez-4
        glVertex3f 0,-2*h/3, myscreen.eyez-4
        glVertex3f 0,0, myscreen.eyez-4
        glVertex3f w/2,-h, myscreen.eyez-4
    glEnd

'glscalef 1/1.4,1/1.4,1
'gltranslatef -2,8,0

   'arrow
    glBegin GL_TRIANGLE_STRIP
        glColor4ub 105,105,205,ma
        glVertex3f -w/2,-h, myscreen.eyez
        glColor4ub 255,255,255,ma
        glVertex3f 0,-2*h/3, myscreen.eyez
        glVertex3f 0,0, myscreen.eyez
        glVertex3f w/2,-h, myscreen.eyez
    glEnd

    glLineWidth 1.5*myscreen.ratiox*_osgl_menuscale

    'outline
    glBegin GL_LINE_LOOP
        glColor4ub 0,0,0,ma
        glVertex3f -w/2,-h, myscreen.eyez
        glVertex3f 0,-2*h/3, myscreen.eyez
        glVertex3f w/2,-h, myscreen.eyez
        glVertex3f 0,0, myscreen.eyez
    glEnd

glLineWidth 1
glEnable GL_TEXTURE_2D
glPopMatrix

else 'myscreen.mousetouchscreen<>0

'if myscreen.mousebuttons<>0 then
	osgl_print x,-y,0,"X",0.5+ma/100-.4*myscreen.mouseinactive/_osgl_mousetimeout,0.25+ma/200-.2*myscreen.mouseinactive/_osgl_mousetimeout,1,3,rgba(255,255,255,ma-150*myscreen.mouseinactive/_osgl_mousetimeout)
'end if


end if 'myscreen.mousetouchscreen



end sub

dim shared as integer _osgl_bordertype=3

sub osgl_DrawBorder (byval x1 as integer, byval y1 as integer, byval x2 as integer, byval y2 as integer, byval style as integer=-999,byval usearrow as integer=0,byval alphavalue as single=1.0)
if style=-999 then style=_osgl_bordertype
y1=-y1
y2=-y2
static textboxangle as integer
static textboxsin as integer
osgl_SetBlendMode 1
glPushMatrix
select case style
	case -1
	'escurecer
	glDisable GL_TEXTURE_2D

    'box
    'glBegin GL_QUADS
    glBegin GL_TRIANGLE_STRIP
        glColor4ub 0,0,0,100 *alphavalue'-textboxopen/2-textboxend/2
        glVertex3f x1-4*_osgl_menuscale,y1+4*_osgl_menuscale, myscreen.eyez
        glVertex3f x2+4*_osgl_menuscale,y1+4*_osgl_menuscale, myscreen.eyez
        glVertex3f x1-4*_osgl_menuscale,y2-4*_osgl_menuscale, myscreen.eyez
        glVertex3f x2+4*_osgl_menuscale,y2-4*_osgl_menuscale, myscreen.eyez
    glEnd

    case 1:
    'green
    textboxangle+=15
    osgl_wrap(textboxangle,0,359)
    textboxsin=2*sin(radians(textboxangle))

    #IFNDEF _osgl_softrender_

	glDisable GL_TEXTURE_2D

    'box
    'glBegin GL_QUADS
    glBegin GL_TRIANGLE_STRIP
        glColor4ub 15,125,15,200 *alphavalue'-textboxopen/2-textboxend/2
        glVertex3f x1-4*_osgl_menuscale,y1+4*_osgl_menuscale, myscreen.eyez
        glVertex3f x2+4*_osgl_menuscale,y1+4*_osgl_menuscale, myscreen.eyez
        glColor4ub 5,25,5,225 *alphavalue'-textboxopen-textboxend
        glVertex3f x1-4*_osgl_menuscale,y2-4*_osgl_menuscale, myscreen.eyez
        glVertex3f x2+4*_osgl_menuscale,y2-4*_osgl_menuscale, myscreen.eyez
    glEnd

    glLineWidth 2*myscreen.ratiox*_osgl_menuscale

    'outline
    glBegin GL_LINE_LOOP
        glColor4ub 0,0,0,105 *alphavalue '-textboxopen-textboxend
        glVertex3f x1+2*_osgl_menuscale,y1-2*_osgl_menuscale, myscreen.eyez
        glVertex3f x2,y1-2*_osgl_menuscale, myscreen.eyez
        glVertex3f x2,y2, myscreen.eyez
          glVertex3f x1+2*_osgl_menuscale,y2, myscreen.eyez
    glEnd
    glBegin GL_LINE_LOOP
        glColor4ub 255,255,255,255 *alphavalue '-textboxopen-textboxend
        glVertex3f x1,y1, myscreen.eyez
        glVertex3f x2-2*_osgl_menuscale,y1, myscreen.eyez
        glVertex3f x2-2*_osgl_menuscale,y2+2*_osgl_menuscale, myscreen.eyez
          glVertex3f x1,y2+2*_osgl_menuscale, myscreen.eyez
    glEnd


    if usearrow then
    'arrow
    glBegin GL_LINE_LOOP
        glColor4ub 255,255,255,255 *alphavalue '-textboxopen-textboxend
        glVertex3f x2-23*_osgl_menuscale,y2+(15 +textboxsin)*_osgl_menuscale, myscreen.eyez
        glVertex3f x2-5*_osgl_menuscale,y2+(15 +textboxsin)*_osgl_menuscale, myscreen.eyez
        glVertex3f x2-14*_osgl_menuscale,y2+(6 +textboxsin)*_osgl_menuscale, myscreen.eyez
    glEnd

    end if
    #endif

    case 2:
    'blue
    textboxangle+=15
    osgl_wrap(textboxangle,0,359)
    textboxsin=2*sin(radians(textboxangle))

    #IFNDEF _osgl_softrender_
	glDisable GL_TEXTURE_2D

    'shadow
    glBegin GL_TRIANGLE_STRIP
        glColor4ub 0,0,0,32 * alphavalue '-textboxopen/2-textboxend/2
        glVertex3f x1-4+8,y1+4-8, myscreen.eyez
        glVertex3f x2+4+8,y1+4-8, myscreen.eyez
        glVertex3f x1-4+8,y2-4-8, myscreen.eyez
        glVertex3f x2+4+8,y2-4-8, myscreen.eyez
    glEnd

    'box
    glBegin GL_TRIANGLE_STRIP
        glColor4ub 75,75,195,120 * alphavalue'-textboxopen/2-textboxend/2
        glVertex3f x1-4,y1+4, myscreen.eyez
        glVertex3f x2+4,y1+4, myscreen.eyez
        glColor4ub 15,15,25,255 '-textboxopen-textboxend
          glVertex3f x1-4,y2-4, myscreen.eyez
        glVertex3f x2+4,y2-4, myscreen.eyez
    glEnd

    glLineWidth 2*myscreen.ratiox

    'outline
    glBegin GL_LINE_LOOP
        glColor4ub 255,255,255,255 * alphavalue'-textboxopen-textboxend
        glVertex3f x1,y1, myscreen.eyez
        glVertex3f x2,y1, myscreen.eyez
        glVertex3f x2,y2, myscreen.eyez
          glVertex3f x1,y2, myscreen.eyez
    glEnd

    if usearrow then
    'arrow
    glBegin GL_LINE_LOOP
        glColor4ub 255,255,255,255 * alphavalue'-textboxopen-textboxend
        glVertex3f x2-23,y2+15 +textboxsin, myscreen.eyez
        glVertex3f x2-5,y2+15 +textboxsin, myscreen.eyez
        glVertex3f x2-14,y2+6 +textboxsin, myscreen.eyez
    glEnd

    end if
    #endif

    case 3:
    'ice gelo
    textboxangle+=15
    osgl_wrap(textboxangle,0,359)
    textboxsin=2*sin(radians(textboxangle))

    #IFNDEF _osgl_softrender_

	glDisable GL_TEXTURE_2D

    'box
    'glBegin GL_QUADS
    glBegin GL_TRIANGLE_STRIP
        glColor4ub 230,245,255,150 *alphavalue'-textboxopen/2-textboxend/2
        glVertex3f x1-4,y1+4, myscreen.eyez
        glVertex3f x2+4,y1+4, myscreen.eyez
        glColor4ub 95,135,245,105 *alphavalue'-textboxopen-textboxend
        glVertex3f x1-4,y2-4, myscreen.eyez
        glVertex3f x2+4,y2-4, myscreen.eyez
    glEnd

    glLineWidth 2*myscreen.ratiox

    'outline
    glBegin GL_LINE_LOOP
        glColor4ub 0,0,0,105 *alphavalue '-textboxopen-textboxend
        glVertex3f x1+2,y1-2, myscreen.eyez
        glVertex3f x2,y1-2, myscreen.eyez
        glVertex3f x2,y2, myscreen.eyez
          glVertex3f x1+2,y2, myscreen.eyez
    glEnd
    glBegin GL_LINE_LOOP
        glColor4ub 255,255,255,255 *alphavalue '-textboxopen-textboxend
        glVertex3f x1,y1, myscreen.eyez
        glVertex3f x2-2,y1, myscreen.eyez
        glVertex3f x2-2,y2+2, myscreen.eyez
          glVertex3f x1,y2+2, myscreen.eyez
    glEnd


    if usearrow then
    'arrow
    glBegin GL_LINE_LOOP
        glColor4ub 255,255,255,255 *alphavalue '-textboxopen-textboxend
        glVertex3f x2-23,y2+15 +textboxsin, myscreen.eyez
        glVertex3f x2-5,y2+15 +textboxsin, myscreen.eyez
        glVertex3f x2-14,y2+6 +textboxsin, myscreen.eyez
    glEnd

    end if
    #endif

    case else
end select
#IFNDEF _osgl_softrender_
glLineWidth 1
glEnable GL_TEXTURE_2D
glPopMatrix
#endif
end sub


function osgl_TextBoxTask (text as string, byval pressbutton as integer=-999,byval bordertype as integer=-999, clicksound as integer=-999,usearrow as integer=1) as integer
'loop until osgl_textbox(sprite_textbox,a4,osgl_button(1,1)=1 or osgl_button(1,2)=1,0)
if bordertype=-999 then bordertype=_osgl_bordertype
static textboxstart as integer
static textboxopen as integer
static textboxend as integer
static textboxgetnewtext as integer
static textboxtimer as integer
static textboxblink as integer
static textboxcurrent as integer
static textboxstring as string
dim as string tmpstring=text
dim as string textboxstringbak
dim as integer x1,x2,y1,y2

if textboxgetnewtext=0 then
select case textboxopen
    case 0:
        textboxgetnewtext=1
        textboxtimer=45
        textboxopen=200-_osgl_textboxoffset
	osgl_pollinput_keyboard()
        osgl_pollinput()
        StringASCII(tmpstring)
        osgl_StringLineWrap(tmpstring,linechars)
        textboxstringbak=textboxstring
        textboxstring=StringFromList(tmpstring,textboxcurrent+1,chr(10))+chr(10)+StringFromList(tmpstring,textboxcurrent+2,chr(10))+chr(10)+StringFromList(tmpstring,textboxcurrent+3,chr(10))
    case -1:
        textboxgetnewtext=1
        StringASCII(tmpstring)
        osgl_StringLineWrap(tmpstring,linechars)
        textboxstringbak=textboxstring
        textboxstring=StringFromList(tmpstring,textboxcurrent+1,chr(10))+chr(10)+StringFromList(tmpstring,textboxcurrent+2,chr(10))+chr(10)+StringFromList(tmpstring,textboxcurrent+3,chr(10))
end select
end if

'textboxopen-=12
textboxopen=textboxopen*.9 - 5
if textboxopen<1 then textboxopen=1

if textboxstring=chr(10,10) then
    textboxend=1
    textboxstring=textboxstringbak
    textboxtimer=0
end if

if textboxend then
    'textboxend+=12
    textboxend=textboxend*1.2 + 5
    textboxopen=1
end if

if textboxend>=(200-_osgl_textboxoffset) then
    textboxstart=0
    textboxopen=0
    textboxgetnewtext=0
    textboxblink=0
    textboxcurrent=0
    textboxend=0
    textboxstring=""
    return 1
end if

dim as single scale2=_osgl_menuscale*myscreen.y/200

x1=(20*scale2-myscreen.x/2+myscreen.widepixels)
x2=(myscreen.x/2-20*scale2-myscreen.widepixels)
y1=(myscreen.y/2-140*scale2+(textboxopen+textboxend)*scale2)+_osgl_textboxoffset
y2=(myscreen.y/2-10*scale2+(textboxopen+textboxend)*scale2)+_osgl_textboxoffset

dim as single mya=(200-_osgl_textboxoffset-textboxopen-textboxend)/(200-_osgl_textboxoffset)

if mya>.1 then

	osgl_drawborder(x1,y1,x2,y2,bordertype,usearrow, mya)

	osgl_print(x1+10*scale2,y1+10*scale2,0,textboxstring,1.6*scale2,1.8*scale2,0,1,rgba(255,255,255,255*mya))

end if

if pressbutton=-999 then pressbutton=(osgl_button(_osgl_menuplayer)=1) or multikey(1) or osgl_mousebutton

if textboxtimer=0 then
    if pressbutton then
    if textboxend=0 then
        textboxgetnewtext=0
        textboxtimer=45
        textboxcurrent+=3:textboxopen=-1
		if _osgl_menuclicksound<>0 then osgl_playsound(_osgl_menuclicksound)
    end if
    end if
else
    textboxtimer-=4
    if textboxtimer<0 then textboxtimer=0
end if

return 0
end function


sub osgl_setmenusounds(movesound as integer=0,clicksound as integer=0)
_osgl_menumovesound=movesound
_osgl_menuclicksound=clicksound
end sub

sub osgl_setmenuplayer(player as integer=1)
_osgl_menuplayer=player
end sub


function osgl_MenuTask(byval x as integer,byval y as integer,menuoptions() as string, byval acceptbuttonflag as integer=-999, byval cancelbuttonflag as integer=-999, byval bordertype as integer=-999, byval defaultoption as integer=1) as integer
'osgl_menu(options,acceptbutton,cancelbutton,bordertype,movesound,choosesound)
'separator = chr(10)
if bordertype=-999 then bordertype=_osgl_bordertype
static menucurrentoption as integer
static menustart as integer
static menuwidth as integer
static menuheight as integer
static menutimer as integer
static menuopen as single
static menuangle as integer
static menusin as single
menuangle+=15
if menuangle>360 then menuangle-=360
menusin=sin(radians(menuangle))

dim as integer menulastoption=ubound(menuoptions)
dim as integer menuoldoption
dim as single alphavalue=1.0
dim as integer drawmouse

dim as integer x1,x2,y1,y2, acceptbutton, cancelbutton
if menustart=0 then
    menustart=1
    menucurrentoption=defaultoption
    menuopen=0.0
end if
if menuopen>.99 then
	if cancelbuttonflag=-999 then cancelbutton=(osgl_cancelbutton(_osgl_menuplayer)=1 or multikey(1)) 'ESC
	if acceptbuttonflag=-999 then acceptbutton=(cancelbutton=0) and (osgl_button(_osgl_menuplayer)=1)
end if

if menuwidth=0 then
    for i as integer=1 to menulastoption
        if menuwidth<len(menuoptions(i)) then menuwidth=len(menuoptions(i))
    next i
end if

if menutimer>0 then
    menutimer-=1
    if osgl_axis(_osgl_menuplayer,2,.1)=0 then
	if osgl_upkey=0 then
	if osgl_downkey=0 then
		menutimer=0
	end if
	end if
	end if
end if

if menutimer=0 then
    if osgl_axis(_osgl_menuplayer,2,.1)>.5 or multikey(&h50) then
		myscreen.mouseinactive=_osgl_mousetimeout
        menucurrentoption+=1
        menutimer=15
		if _osgl_menumovesound<>0 then osgl_playsound(_osgl_menumovesound)
    end if
    if osgl_axis(_osgl_menuplayer,2,.1)<-.5 or multikey(&h48) then
		myscreen.mouseinactive=_osgl_mousetimeout
        menucurrentoption-=1
        menutimer=15
		if _osgl_menumovesound<>0 then osgl_playsound(_osgl_menumovesound)
    end if
end if
osgl_wrap(menucurrentoption,1,menulastoption)

if menuopen<1 then
    menuopen+=.085
    if menuopen>1 then menuopen=1
end if

dim as integer tmp, xoff, yoff

tmp=20+16*menuwidth-(16*menuwidth)*(1-menuopen)
x1=x-(tmp/2)*_osgl_menuscale
x2=x+(tmp/2)*_osgl_menuscale

tmp=8+ubound(menuoptions)*18*2.0-7
y1=y-(tmp/2)*_osgl_menuscale
y2=y+(tmp/2)*_osgl_menuscale

'tweak para o menu ficar sempre dentro da tela

'if y1<-myscreen.y/2 then
'	yoff=y1-myscreen.y/2
'	y-=yoff
'	y1-=yoff
'	y2-=yoff
'end if

'if y2>myscreen.y/2 then
'	yoff=myscreen.y/2-y2
'	y+=yoff
'	y1+=yoff
'	y2+=yoff
'end if

if menuopen>.99 then
if myscreen.mouseclip=0 then
if myscreen.mouseinactive<_osgl_mousetimeout then
	drawmouse=1
	if myscreen.mousey<-y1-8*_osgl_menuscale then 'mouse select
	if myscreen.mousey>-y1-(32*menulastoption+2)*_osgl_menuscale then
	if myscreen.mousex<x2 then
	if myscreen.mousex>x1 then
		menuoldoption=menucurrentoption
		menucurrentoption=(-myscreen.mousey-y1+16*_osgl_menuscale)/(32*_osgl_menuscale)
		if menucurrentoption>menulastoption then menucurrentoption=menulastoption
		if menuoldoption<>menucurrentoption then
			if _osgl_menumovesound<>0 then osgl_playsound(_osgl_menumovesound)
		end if
		if myscreen.mousebuttons=1 then acceptbutton=1 : drawmouse=0
		if myscreen.mousebuttons=2 then cancelbutton=1 : drawmouse=0
	end if
	end if
	end if
	end if
end if
end if
end if

if acceptbutton or cancelbutton then drawmouse=0 : alphavalue=0.25'menu desativado

osgl_drawborder(x1,y1,x2,y2,bordertype,0,menuopen * alphavalue)

for ii as integer=0 to ubound(menuoptions)-1
'    if ii<>menucurrentoption-1 then osgl_print x1+10+(8*menuwidth)*(1-menuopen),y1+16+32*ii,0,menuoptions(ii+1),1.6*menuopen,1.5,0,1,rgba(255,255,255,255*menuopen*alphavalue)
    if ii<>menucurrentoption-1 then osgl_print x1+10*_osgl_menuscale,y1+(10+32*ii)*_osgl_menuscale,0,menuoptions(ii+1),1.6*menuopen*_osgl_menuscale,1.5*_osgl_menuscale,0,1,rgba(255,255,255,255*menuopen*alphavalue)
next ii

'osgl_print x1+8+(8*menuwidth)*(1-menuopen),y1+14+32*(menucurrentoption-1),0,menuoptions(menucurrentoption),1.65*menuopen,1.53,0,1,rgba(255,80-80*menusin,15,255*menuopen*alphavalue)
osgl_print x1+8*_osgl_menuscale,y1+(8+32*(menucurrentoption-1))*_osgl_menuscale,0,menuoptions(menucurrentoption),1.65*menuopen*_osgl_menuscale,1.53*_osgl_menuscale,0,1,rgba(255,80-80*menusin,15,255*menuopen*alphavalue)

function=0

if cancelbutton then
	menucurrentoption=-1
	acceptbutton=1
end if

if acceptbutton then
	if _osgl_menuclicksound<>0 then osgl_playsound(_osgl_menuclicksound)
	function=menucurrentoption
	menucurrentoption=1
	menustart=0
	menuwidth=0
	menuheight=0
	menutimer=0
	menuopen=0
	menuangle=0
	menusin=0
	drawmouse=0
	osgl_waitkeyrelease
	osgl_sync
end if

'if drawmouse then osgl_drawmouse

end function


sub osgl_TextBox (text as string, byval bordertype as integer=-999, clicksound as integer=-999)
if bordertype=-999 then bordertype=_osgl_bordertype
'dim as integer screencapture=0
'osgl_CaptureScreenAsTexture(screencapture)
osgl_storeframebuffer

osgl_suspendcamera

osgl_playsound(_osgl_menumovesound)

dim as integer passtext

do
osgl_restoreframebuffer
'osgl_quad(    -myscreen.x/2,-myscreen.y/2,_
'            myscreen.x/2,myscreen.y/2,_
'            0,_
'            screencapture,0,_
'            0,0,_     'mirror,flip
'            1,1,0,0,_   '        xrep,yrep,xscroll,yscroll,_
'            7,0,_       '        blendmode,depthtest,_
'             255,255,255,255)    '        r,g,b,a)

        passtext=osgl_TextBoxTask (text,,bordertype,clicksound)
	sleep 1,1
        osgl_sync
        osgl_pollosevents 'poll events
'printconsole "*****menu loops! "+str(getchoice)
loop until passtext
'osgl_deletetexture(screencapture)

osgl_restoreframebuffer
osgl_sync
osgl_syncbuffers

osgl_restorecamera
end sub



sub osgl_syncbuffers1()
printdebug "Screen : Syncing buffers..."

if myscreen.usefrontbuffer then
	
	osgl_SetBlendMode(0)
	
	glReadBuffer GL_FRONT 'crashes intel

	for i as integer=1 to 3

		glCopyPixels(0,0, myscreen.realx, myscreen.realy, GL_COLOR)
		'osgl_sync
		flip

	next i

	glReadBuffer GL_BACK

else

	flip
	osgl_storeframebuffer(1)
	for i as integer=1 to 3
		osgl_restoreframebuffer
		flip
	next i

end if

end sub




sub osgl_syncbuffers()
printdebug "Screen : Syncing buffers..."
osgl_storeframebuffer(1)
for i as integer=1 to 3
osgl_restoreframebuffer
osgl_sync(1)
next i
end sub


sub osgl_syncbuffers2
#IFNDEF _osgl_softrender
printdebug "Screen : Syncing buffers..."
dim as any ptr capture=imagecreate(myscreen.realx,myscreen.realy,rgba(0,0,0,255),32)
Dim As uByte Ptr pixels
ImageInfo capture,,,,,pixels
glDisable(GL_TEXTURE_2D)
glFlush
glReadPixels(0,0,myscreen.realx,myscreen.realy,GL_RGB,GL_UNSIGNED_BYTE,pixels)
for i as integer=1 to 3
glRasterPos2f(-myscreen.x/2,-myscreen.y/2+.0001)
glDrawPixels(myscreen.realx,myscreen.realy,GL_RGB,GL_UNSIGNED_BYTE,pixels)
flip
sleep 1,1
next i
if capture then imagedestroy capture
myscreen.frameskipcounter=0
#ENDIF
end sub


sub osgl_syncbuffers__
#IFNDEF _osgl_softrender
'exit sub
'glflush
'glReadBuffer (GL_FRONT)
'glDrawBuffer (GL_BACK)
'glReadBuffer (GL_BACK)
'glDrawBuffer (GL_FRONT)
for i as integer=1 to 3
glRasterPos2f(-myscreen.x/2,myscreen.y/2-.0001)
'glCopyPixels (-320,240,myscreen.realx,myscreen.realy,GL_COLOR)
glCopyPixels (0,0,myscreen.realx,myscreen.realy,GL_COLOR)
flip
sleep 1,1
next i
'glReadBuffer (GL_BACK)
'glDrawBuffer( GL_BACK )
myscreen.frameskipcounter=0
#ENDIF
end sub


sub osgl_syncbuffers_
#IFNDEF _osgl_softrender_
exit sub
printdebug "Screen : Syncing buffers..."
dim as any ptr capture=imagecreate(myscreen.realx,myscreen.realy,rgba(0,0,0,255),32)
Dim As uByte Ptr pixels
ImageInfo capture,,,,,pixels
glDisable(GL_TEXTURE_2D)
glFlush
glReadPixels(0,0,myscreen.realx,myscreen.realy,GL_RGB,GL_UNSIGNED_BYTE,pixels)
flip
'glDrawBuffer(GL_FRONT_AND_BACK)
glRasterPos2f(-myscreen.x/2,myscreen.y/2-.0001)
glDrawPixels(myscreen.realx,myscreen.realy,GL_RGB,GL_UNSIGNED_BYTE,pixels)
'glDrawBuffer( GL_BACK )
if capture then imagedestroy capture
myscreen.frameskipcounter=0
#ENDIF
end sub


function osgl_Menu(byval x as integer=0,byval y as integer=0,question as string="",optionlist as string, byval bordertype as integer=-999) as integer
if bordertype=-999 then bordertype=_osgl_bordertype
'dim as integer screencapture=0
'osgl_CaptureScreenAsTexture(screencapture)
dim as integer getchoice=0, getchoice1=0
dim as integer passtext=0
dim as string menuchoicearr()
dim as integer qnumlines=1, mnumlines=1, defaultoption=1

for i as integer=1 to len(question)-1
	if mid(question,i,2)=CRLF then qnumlines+=1
next i

for i as integer=1 to len(optionlist)
	if mid(optionlist,i,1)="," then mnumlines+=1
next i

                dim as integer x1=-myscreen.x/2+20+myscreen.widepixels
                dim as integer x2=myscreen.x/2-20-myscreen.widepixels
                'dim as integer y1=myscreen.y/2-140
                'dim as integer y2=myscreen.y/2-10
                'dim as integer y1=-230
                'dim as integer y2=-120
                'dim as integer y1=y-24*(mnumlines+qnumlines+1)
                'dim as integer y2=y1+48*qnumlines
                dim as integer y2=y-22*(mnumlines)*_osgl_menuscale
				dim as integer y1=y2-48*qnumlines*_osgl_menuscale

				if y1<-myscreen.y/2 then
					y2=myscreen.y/2-4
					y1=y2-48*qnumlines*_osgl_menuscale
				end if

				if y2>myscreen.y/2 then
					y1=-236
					y2=y1+48*qnumlines*_osgl_menuscale
				end if

x1=x1*_osgl_menuscale
x2=x2*_osgl_menuscale
'y1=y1*_osgl_menuscale
'y2=y2*_osgl_menuscale

osgl_syncbuffers

osgl_suspendcamera

osgl_storeframebuffer

String2Array(optionlist,",",menuchoicearr())

for i as integer=1 to ubound(menuchoicearr)
	if mid(menuchoicearr(i),1,1)="_" then
		menuchoicearr(i)=right(menuchoicearr(i),len(menuchoicearr(i))-1)
		defaultoption=i
	end if
next i

osgl_waitkeyrelease

do

'osgl_quad(    -myscreen.x/2,-myscreen.y/2,_
'            myscreen.x/2,myscreen.y/2,_
'            0,_
'            screencapture,0,_
'            0,0,_     'mirror,flip
'            1,1,0,0,_   '        xrep,yrep,xscroll,yscroll,_
'            7,0,_       '        blendmode,depthtest,_
'            255,255,255,255)    '        r,g,b,a)

        osgl_sync

        osgl_pollosevents 'poll events

		osgl_restoreframebuffer

        getchoice=osgl_menutask(x,y,menuchoicearr(),-999,-999,bordertype,defaultoption)

		if getchoice=0 then
			if question<>"" then
                osgl_drawborder(x1,y1,x2,y2,bordertype,0,1)
                'osgl_print(x1+10,y1+10,0,question,1.6,1.8,0,1,rgba(255,255,255,255))
                osgl_print((x1+x2)/2,y1+10*_osgl_menuscale,0,question,1.6*_osgl_menuscale,1.8*_osgl_menuscale,1,1,rgba(255,255,255,255))
			end if
			osgl_drawmouse
		end if


loop until getchoice

osgl_syncbuffers

'if question<>"" then
'osgl_quad(    0,0,_
'            myscreen.x,myscreen.y,_
'            0,_
'            screencapture,0,_
'            0,0,_     'mirror,flip
'            1,1,0,0,_   '        xrep,yrep,xscroll,yscroll,_
'            7,0,_       '        blendmode,depthtest,_
'            255,255,255,255)    '        r,g,b,a)


'end if

'osgl_deletetexture(screencapture)
'osgl_syncbuffers
'osgl_waitkeyrelease
'osgl_sync
osgl_restorecamera

'osgl_sync

function=getchoice
end function




function osgl_numbermenu(byval x1 as integer=0, byval y1 as integer=0, question as string="", byval first as integer=1,byval last as integer=1, byval default as integer=1) as integer
dim as integer x2=x1+32*3*_osgl_menuscale,y2=y1+36*_osgl_menuscale
dim as integer getchoice=default
dim as integer holdkey, getbut, getcbut
dim menuangle as integer
dim menusin as single
dim as integer xcur, xcurold, ycur, ycurold, mnumlines=1, qnumlines=1, mousebut, mousecbut
dim as single xaxis=0, yaxis=0

dim as single scale2=_osgl_menuscale*myscreen.y/200

dim as integer xd=x2-x1
x1=x1-xd/2
x2=x2-xd/2



                dim as integer x1a=-myscreen.x/2+20*scale2+myscreen.widepixels
                dim as integer x2a=myscreen.x/2-20*scale2-myscreen.widepixels
                dim as integer y2a=y1-22*mnumlines
				dim as integer y1a=y2a-48*qnumlines

				if y1a<-myscreen.y/2 then
					y2a=myscreen.y/2-4*scale2
					y1a=y2a-48*scale2
				end if

				if y2a>myscreen.y/2 then
					y1a=-236*scale2
					y2a=y1a+48*scale2
				end if

				x1a=x1a*_osgl_menuscale
				x2a=x2a*_osgl_menuscale
				y1a=y1a*_osgl_menuscale
				y2a=y2a*_osgl_menuscale


osgl_syncbuffers

osgl_sync(1)

osgl_storeframebuffer

osgl_suspendcamera

osgl_waitkeyrelease


do

menuangle+=15
if menuangle>360 then menuangle-=360
menusin=sin(radians(menuangle))

osgl_drawborder(x1,y1,x2,y2,_osgl_bordertype,0,1)

'osgl_print(x1+32*getchoice-16,(y1+y2)/2-12,0,str(getchoice),2.0+.05*menusin,1.7+.05*menusin,1,1,rgba(255,80-80*menusin,15,255))

osgl_print(x1+(32*2-16)*_osgl_menuscale,(y1+y2)/2-12*_osgl_menuscale,0,"<   >",(1.8+.1*menusin)*_osgl_menuscale,1.4*_osgl_menuscale,1,1,rgba(255,255,255,255))

osgl_print(x1+(32*2-16)*_osgl_menuscale,(y1+y2)/2-12*_osgl_menuscale,0,str(getchoice),2.0*_osgl_menuscale, 1.7*_osgl_menuscale ,1,1,rgba(255,80-80*menusin,15,255))

osgl_drawmouse

osgl_sync

osgl_pollosevents 'poll events

osgl_restoreframebuffer

mousebut=osgl_mousebutton(1)
mousecbut=osgl_mousebutton(2)

'printconsole mousebut; mousecbut

if holdkey<>0 then
	if abs(xaxis)<.4 then
	if mousebut=0 then
	if mousecbut=0 then
		holdkey=0
	end if
	end if
	end if
else
	if xaxis<-.5 then
		getchoice-=1 : holdkey=-1 : osgl_mousehide
		if _osgl_menumovesound<>0 then osgl_playsound(_osgl_menumovesound)
	end if

	if xaxis>.5 then
		getchoice+=1 : holdkey=1 : osgl_mousehide
		if _osgl_menumovesound<>0 then osgl_playsound(_osgl_menumovesound)
	end if

	osgl_wrap(getchoice,first,last)
end if


if getcbut=0 then getcbut=osgl_cancelbutton(_osgl_menuplayer)
if getcbut=0 then getcbut=mousecbut
if getcbut=0 then getcbut=osgl_esckey

if getcbut=0 then
	if getbut=0 then getbut=osgl_button(_osgl_menuplayer)
	if getbut=0 then getbut=osgl_enterkey
end if

xaxis=osgl_axis(_osgl_menuplayer,1)
yaxis=osgl_axis(_osgl_menuplayer,2)

'printconsole myscreen.mousey/scale2; y1/scale2; y2/scale2

if mousebut then
'if 0=0 then

					if myscreen.mouseclip=0 then
					if holdkey=0 then

						getbut=0 : getcbut=0 : holdkey=1

						if myscreen.mousey/scale2>-y2/scale2 then
						if myscreen.mousey/scale2<-y1/scale2 then
							
							xcurold=(myscreen.mousex/scale2-x1/scale2+16)/32

							'xcurold=1+((myscreen.mousex/scale2-x1/scale2-10)/24)
							'ycurold=2+((-myscreen.mousey/scale2+y0/scale2+10)/25)


							select case xcurold
								case 3
									getchoice+=1 : getbut=0 : getcbut=0 : holdkey=1
									if _osgl_menumovesound<>0 then osgl_playsound(_osgl_menumovesound)
								case 1
									getchoice-=1 : getbut=0 : getcbut=0 : holdkey=-1
									if _osgl_menumovesound<>0 then osgl_playsound(_osgl_menumovesound)
								case 2
									getbut=1 : getcbut=0 : holdkey=1
								case else
									getbut=0 : getcbut=0 : holdkey=1
							end select

							osgl_wrap(getchoice,first,last)

						end if
						end if


					end if
					end if
end if


		if question<>"" then
            osgl_drawborder(x1a,y1a,x2a,y2a,_osgl_bordertype,0,1)
            'osgl_print(x1a+10,y1a+10,0,question,1.6,1.8,0,1,rgba(255,255,255,255))
            osgl_print((x1a+x2a)/2,y1a+10*scale2,0,question,1.4*_osgl_menuscale,1.6*_osgl_menuscale,1,1,rgba(255,255,255,255))
		end if

'loop until osgl_esckey
loop until getbut or getcbut

if _osgl_menuclicksound<>0 then osgl_playsound(_osgl_menuclicksound)

if getcbut then getchoice=first-1

osgl_sync(1)
osgl_syncbuffers


function=getchoice

end function



'osgl_Menu(byval x as integer=0,byval y as integer=0,question as string="",optionlist as string, byval bordertype as integer=0, byval movesound as integer=-999, choosesound as integer=-999) as integer
function osgl_systemmenu as integer
dim as integer m1=0
dim as integer m2=0
dim as integer m3=0
osgl_storeframebuffer
do
osgl_restoreframebuffer
m1=osgl_menu (-200,-200,"","Video,3D Stereo,Audio,Controllers,Game,Save Settings,Discard All Changes and Quit",1)
select case m1
	case 1: m2=osgl_menu (-200,-200,"","Screen Mode,Fullscreen,Vsync,Antialias,Frameskip",1)
			select case m2
				case 1:m3=osgl_menu (-200,-200,"","Auto,640x480",1)
				case 2:m3=osgl_menu (-200,-200,"","On (recommended),Off",1)
				case 3:m3=osgl_menu (-200,-200,"","On (recommended),Off",1)
				case 4:m3=osgl_menu (-200,-200,"","On,Off",1)
				case 5:m3=osgl_menu (-200,-200,"","Off (recommended),On",1)
			end select
	case 2: m2=osgl_menu (-200,-200,"","Disabled,Anaglyph,OpenGL",1)
	case 3: m2=osgl_menu (-200,-200,"","Music,Sound Effects",1)
			m3=osgl_menu (-200,-200,"","On,Off",1)
	case 4: m2=osgl_menu (-200,-200,"","Set Keys For Player 1,Set Keys For Player 2,Select Controller For Player 1,Configure Buttons For Player 1,Select Controller For Player 2,Configure Buttons For Player 2,Select Controller For Player 3,Configure Buttons For Player 3,Select Controller For Player 4,Configure Buttons For Player 4",1)
	case 5: m2=osgl_menu (-200,-200,"","Game Mode,Difficulty,Coins",1)
			select case m2
				case 1:m3=osgl_menu (-200,-200,"","Console,Arcade",1)
				case 2:m3=osgl_menu (-200,-200,"","Easy,Normal,Hard,Ultimate",1)
				case 3:m3=osgl_menu (-200,-200,"","1 coin=1 credit,2 coins=1 credit,1 coin=2 credits",1)
			end select
	case else: return 0
end select
loop
return 0
end function


function osgl_StringChange(instring as string,inchar as string,outchar as string) as string
dim as integer ascinchar=asc(inchar)
dim as integer ascoutchar=asc(outchar)
for i as integer=0 to len(instring)
    if instring[i]=ascinchar then instring[i]=ascoutchar
next i
return instring
end function


sub osgl_Screenshot()
dim as string filename=homedir+appname()+"-screenshot-"+date+"-"+osgl_StringChange(time,":","-")+".png"
printdebug "Screenshot : Saving "+filename
dim as any ptr capture=imagecreate(myscreen.realx,myscreen.realy,rgba(0,0,0,255),32)
dim as any ptr capture2=imagecreate(myscreen.realx,myscreen.realy,rgba(0,0,0,255),32)
Dim As uByte Ptr pixels
ImageInfo capture,,,,,pixels
#IFNDEF _osgl_softrender_
glReadPixels(0,0,myscreen.realx,myscreen.realy,GL_RGBA,GL_UNSIGNED_BYTE,pixels)
#endif
'glReadPixels(myscreen.x,myscreen.y,myscreen.realx,myscreen.realy,GL_BGRA,GL_UNSIGNED_BYTE,pixels)
osgl_imageRGBA2BGRA(capture)
rotozoom capture2,capture,myscreen.realx/2,myscreen.realy/2,0,1,-1,
'bsave filename, capture
'filename="/tmp/fbfont.png"
osgl_SavePNG filename, capture2
if capture then imagedestroy capture : capture=0
if capture2 then imagedestroy capture2 : capture2=0
end sub


sub osgl_FadeIn(byval effect as integer=0,byval speed as single=1.0)
myscreen.fadeinspeed=speed
myscreen.FadeIneffect=effect
myscreen.FadeInalpha=255
end sub


sub osgl_FadeInDraw(byval effect as integer=0,byval a as integer=0)
if a=0 then exit sub
if myscreen.useopengl=0 then
    'screencontrol SET_ALPHA_PRIMITIVES, 1
    'line (0,0)-(myscreen.x,myscreen.y),rgba(0,0,0,a),BF
    'screencontrol SET_ALPHA_PRIMITIVES, 0
    exit sub
end if

    #IFNDEF _osgl_softrender_
    glPushMatrix
    osgl_SetBlendMode(1)
    osgl_suspendcamera
	glDisable GL_TEXTURE_2D
    'glBegin GL_QUADS
 '   glBegin GL_TRIANGLE_STRIP
select case as const effect
	case 1:	glColor4ub 255,255,255,a
	case else: glColor4ub 0,0,0,a
end select
 '       glVertex2f -myscreen.x/2,-myscreen.y/2
  '      glVertex2f -myscreen.x/2,myscreen.y/2
   '     glVertex2f myscreen.x/2,-myscreen.y/2
    '    glVertex2f myscreen.x/2,myscreen.y/2
   ' glEnd
   gltranslatef 0,0,myscreen.eyez
       glquad3d(-myscreen.x/2,-myscreen.y/2,0,myscreen.x/2,-myscreen.y/2,0,-myscreen.x/2,myscreen.y/2,0,myscreen.x/2,myscreen.y/2,0)
'    glquad3d( textureprecalc.sx(0),textureprecalc.sy(0),textureprecalc.sz(0),textureprecalc.sx(3),textureprecalc.sy(3),textureprecalc.sz(3),textureprecalc.sx(1),textureprecalc.sy(1),textureprecalc.sz(1),textureprecalc.sx(2),textureprecalc.sy(2),textureprecalc.sz(2),_

    osgl_restorecamera
    glPopMatrix
    #endif
    myscreen.virgin=1
end sub


sub osgl_FadeOut(byval effect as integer=0)
myscreen.FadeInalpha=0
osgl_syncbuffers
if myscreen.useopengl=0 then
    'screencontrol SET_ALPHA_PRIMITIVES,1
    for a as integer=0 to 255 step 5
        'line (0,0)-(myscreen.x,myscreen.y),rgba(0,0,0,a),BF
        'osgl_sync()
    next a
    'screencontrol SET_ALPHA_PRIMITIVES,0
    exit sub
end if
osgl_suspendcamera
osgl_SetBlendMode(1)
select case as const effect
    case 1: 'fade to white
        for i as integer=0 to 255 step 5
                #IFNDEF _osgl_softrender_
                glDisable GL_TEXTURE_2D
                'glBegin GL_QUADS
		if i>250 then i=255
                    glColor4ub 255,255,255,i
			glquad3d(-myscreen.x/2,-myscreen.y/2,myscreen.eyez,myscreen.x/2,-myscreen.y/2,myscreen.eyez,-myscreen.x/2,myscreen.y/2,myscreen.eyez,myscreen.x/2,myscreen.y/2,myscreen.eyez)
                #endif
		myscreen.virgin=1
                osgl_sync()
        next i
    case 2: 'fade to red
        for ii as integer=0 to 255 step 5
                #IFNDEF _osgl_softrender_
                glDisable GL_TEXTURE_2D
                'glBegin GL_QUADS
		if ii>250 then ii=255
                    glColor4ub 255,0,0,ii
			glquad3d(-myscreen.x/2,-myscreen.y/2,myscreen.eyez,myscreen.x/2,-myscreen.y/2,myscreen.eyez,-myscreen.x/2,myscreen.y/2,myscreen.eyez,myscreen.x/2,myscreen.y/2,myscreen.eyez)
                #endif
		myscreen.virgin=1
                osgl_sync()
        next ii
    case 3: 'zoom fade
        'osgl_syncbuffers
        osgl_StoreFrameBuffer()
        for iii as integer=0 to 255 step 5
                #IFNDEF _osgl_softrender_
                glEnable GL_TEXTURE_2D
                #endif
		if iii>250 then iii=255
                    osgl_Render(0,0,0.0,0.0,_ 'x1,y1,xcenter,ycenter,_
                        0,_ 'z,_
                        myscreen.screencopytexture,0,_     '        texturenumber,slices,frame,_
                        iii/5,_ '0,_  'p(i).angle,_
                        1.0*(myscreen.x/myscreen.realx)+3.0*iii/255,1.0*(myscreen.x/myscreen.realx)+3.0*iii/255,0,0,_     'xscale,yscale,xoffset,yoffset,_
                        1.0,1.0,_ 'stretch
                        0,1,_     'mirror,flip
                        1,1,0,0,_   '        xrep,yrep,xscroll,yscroll,_
                        1,0,_       '        blendmode,depthtest,_
			rgba(255-iii,255-iii,255-iii,105),1)
                        '255-i,255-i,255-i,105)    '        r,g,b,a)
                osgl_sync()
        next iii

    case 4: 'zoom fade white
        'osgl_syncbuffers
        osgl_StoreFrameBuffer()
        for i4 as integer=0 to 255 step 1
                #IFNDEF _osgl_softrender_
                glEnable GL_TEXTURE_2D
                #endif
		if i4>250 then i4=255
                    osgl_Render(0,0,0.0,0.0,_ 'x1,y1,xcenter,ycenter,_
                        0,_ 'z,_
                        myscreen.screencopytexture,0,_     '        texturenumber,slices,frame,_
                        i4/6,_ '0,_  'p(i).angle,_
                        1.0*(myscreen.x/myscreen.realx)+4.0*i4/255,1.0*(myscreen.y/myscreen.realy)+4.0*i4/255,0,0,_     'xscale,yscale,xoffset,yoffset,_
                        1.0,1.0,_ 'stretch
                        0,1,_     'mirror,flip
                        1,1,0,0,_   '        xrep,yrep,xscroll,yscroll,_
                        1,0,_       '        blendmode,depthtest,_
			rgba(255,255,255,200-i4/2),1)
                        '255,255,255,200-i/2)    '        r,g,b,a)
                #IFNDEF _osgl_softrender_
                glDisable GL_TEXTURE_2D
                    glColor4ub 255,255,255,i4
			glquad3d(-myscreen.x/2,-myscreen.y/2,myscreen.eyez,myscreen.x/2,-myscreen.y/2,myscreen.eyez,-myscreen.x/2,myscreen.y/2,myscreen.eyez,myscreen.x/2,myscreen.y/2,myscreen.eyez)
                #endif
                i4+=i4/10
                osgl_sync()
        next i4
        for i5 as integer=0 to 255 step 5
            #IFNDEF _osgl_softrender_
            glDisable GL_TEXTURE_2D
            'glBegin GL_QUADS
		if i5>250 then i5=255
                glColor4ub 0,0,0,i5
			glquad3d(-myscreen.x/2,-myscreen.y/2,myscreen.eyez,myscreen.x/2,-myscreen.y/2,myscreen.eyez,-myscreen.x/2,myscreen.y/2,myscreen.eyez,myscreen.x/2,myscreen.y/2,myscreen.eyez)
            #endif
   	    myscreen.virgin=1
            osgl_sync()
        next i5

    case 5: 'zoom out
        'osgl_syncbuffers
        osgl_StoreFrameBuffer()
        for i6 as integer=0 to 255 step 5
		if i6>250 then i6=255
                #IFNDEF _osgl_softrender_
                'glBegin GL_QUADS
                glDisable GL_TEXTURE_2D
			glColor4ub 0,0,0,155
			glquad3d(-myscreen.x/2,-myscreen.y/2,myscreen.eyez,myscreen.x/2,-myscreen.y/2,myscreen.eyez,-myscreen.x/2,myscreen.y/2,myscreen.eyez,myscreen.x/2,myscreen.y/2,myscreen.eyez)
                glEnable GL_TEXTURE_2D
                #endif
                osgl_Render(0,0,0.0,0.0,_ 'x1,y1,xcenter,ycenter,_
                    0,_ 'z,_
                    myscreen.screencopytexture,0,_     '        texturenumber,slices,frame,_
                    0,_ '0,_  'p(i).angle,_
                    (myscreen.x/myscreen.realx)*(1.0-i6/255.0),(myscreen.y/myscreen.realy)*(1.0-i6/255.0),0,0,_     'xscale,yscale,xoffset,yoffset,_
                    1.0,1.0,_ 'stretch
                    0,1,_     'mirror,flip
                    1,1,0,0,_   '        xrep,yrep,xscroll,yscroll,_
                    1,0,_       '        blendmode,depthtest,_
			rgba(255,255,255,255),1)
                    '255,255,255,255)    '        r,g,b,a)
                    'i+=i/10
                osgl_sync()
        next i6
        

    case else: 'fade to black
        for ie as integer=0 to 255 step 5
                #IFNDEF _osgl_softrender_
		if ie>250 then ie=255
                glDisable GL_TEXTURE_2D
                'glBegin GL_QUADS
                    glColor4ub 0,0,0,ie*1.5
			glquad3d(-myscreen.x/2,-myscreen.y/2,myscreen.eyez,myscreen.x/2,-myscreen.y/2,myscreen.eyez,-myscreen.x/2,myscreen.y/2,myscreen.eyez,myscreen.x/2,myscreen.y/2,myscreen.eyez)
                #endif
		myscreen.virgin=1
                osgl_sync()
        next ie


end select
osgl_restorecamera
glPopMatrix
glEnable GL_TEXTURE_2D
end sub


function osgl_pause(byref quitflag as integer=0) as integer
function=0
dim as integer i,i2,screencapture
osgl_CaptureScreenAsTexture(screencapture)
osgl_syncbuffers
osgl_sync
dim as integer svolume=sound.sfxvolume*10
dim as integer mvolume=sound.musicvolume*10
osgl_volume(svolume/2,mvolume/2)
osgl_waitkeyrelease
osgl_delay 5
do
osgl_RestoreScreenFromTexture(screencapture)
osgl_fadeindraw 0,127
osgl_sync
i=osgl_menu(0,0,"Game Paused.","Resume,Quit")
if i=2 then
	osgl_RestoreScreenFromTexture(screencapture)
	osgl_fadeindraw 0,127
	osgl_sync
	i2=osgl_menu(0,0,"Quit game. Are you sure?","Yes,No")
	if i2=1 then
		osgl_deletetexture(screencapture)
		osgl_fadeout
		'osgl_end
		quitflag=1
		osgl_volume(svolume,mvolume)
		function=1
		exit function
	end if
	osgl_delay 5
end if
loop until i=1 or i=-1
osgl_deletetexture(screencapture)
osgl_volume(svolume,mvolume)
end function


dim shared virtkeyboard(1 to 40) as string*1
for i as integer=1 to 10
	virtkeyboard(i)=str(i-1)
next i
for i as integer=65 to 90
	virtkeyboard(i-54)=chr(i)
next i
virtkeyboard(37)="."
virtkeyboard(38)=" "
virtkeyboard(39)=" "
virtkeyboard(40)=" "


function osgl_input(byval question as string, byval numchars as integer=linechars, byval bordertype as integer=-999) as string
osgl_waitkeyrelease
if bordertype=-999 then bordertype=_osgl_bordertype
dim as integer screencapture=0
osgl_CaptureScreenAsTexture(screencapture)
dim as string outs=""
dim as string akey=""
dim as integer vkey=0, holdkey=0, holdkey2=0, mclip=1
dim menuangle as integer
dim menusin as single
dim as single xa,ya
dim getchoice as integer=0
dim as integer xcur, ycur, xcurold, ycurold, backspace, enter, offsetbak, usekbdbak

usekbdbak=osgl_playerinput(_osgl_menuplayer).usekeyboard=1
osgl_playerinput(_osgl_menuplayer).usekeyboard=0  'desabilita os controles do teclado temporariamente

offsetbak=_osgl_textboxoffset
_osgl_textboxoffset=0 'desabilita o offset temporariamente

dim as single scale2=_osgl_menuscale*myscreen.y/200

dim as integer x1=(20*scale2-myscreen.x/2+myscreen.widepixels)
dim as integer x2=(myscreen.x/2-20*scale2-myscreen.widepixels)
dim as integer y0=(myscreen.y/2-270*scale2)+_osgl_textboxoffset
dim as integer y1=(myscreen.y/2-140*scale2)+_osgl_textboxoffset
dim as integer y2=(myscreen.y/2-10*scale2)+_osgl_textboxoffset

                'dim as integer x1=-myscreen.x/2+20
                'dim as integer x2=myscreen.x/2-20
				'dim as integer y0=myscreen.y/2-270
                'dim as integer y1=myscreen.y/2-140
                'dim as integer y2=myscreen.y/2-10

do
        osgl_sync
		osgl_pollosevents 'poll events

            osgl_quad(    -myscreen.x/2,myscreen.y/2,_
            myscreen.x/2,-myscreen.y/2,_
            0,_
            screencapture,0,_
            0,0,_     'mirror,flip
            1,1,0,0,_   '        xrep,yrep,xscroll,yscroll,_
            7,0,_       '        blendmode,depthtest,_
            rgba(255,255,255,255))    '        r,g,b,a)

			mclip=1
            akey=inkey()
            vkey=asc(akey)
            if akey<>"" then
            if vkey>=(&h20) and vkey<=(&h7a) then
                outs=left(outs+akey,numchars)
				if _osgl_menuclicksound<>0 then osgl_playsound(_osgl_menuclicksound)
            end if
            end if
			if vkey then
				myscreen.mouseinactive=_osgl_mousetimeout : myscreen.mouseclip=1
			end if


            if backspace then
				backspace=0
                if holdkey=0 then
                    outs=mid(outs,1,len(outs)-1)
                    holdkey=1
					if _osgl_menuclicksound<>0 then osgl_playsound(_osgl_menuclicksound)
                end if
            else
                holdkey=0
            end if

            if enter then enter=0 : getchoice=1

            if getchoice=0 then

				backspace=multikey(&h0E)
				enter=multikey(28)

                if question<>"" then

                    osgl_drawborder(x1,y0-5*scale2,x1+250*scale2,y1-20*scale2,bordertype,0,1)

					dim as integer k=0
					for j as integer=1 to 4
					for i as integer=1 to 10
						k+=1
						osgl_print(x1+(10+24*(i-1))*scale2,y0+(25*(j-1))*scale2,0, virtkeyboard(k) ,1.6*scale2,1.7*scale2,0,1,rgba(255,255,255,255))
					next i
					next j
						osgl_print(x1+(10+24*( 8-1))*scale2,y0+(25*(4-1))*scale2,0, "SPACE" ,0.35*scale2,1.0*scale2,0,1,rgba(255,255,255,255))
						osgl_print(x1+(10+24*( 9-1))*scale2,y0+(25*(4-1))*scale2,0, "<-" ,0.75*scale2,1.0*scale2,0,1,rgba(255,255,255,255))
						osgl_print(x1+(10+24*(10-1))*scale2,y0+(25*(4-1))*scale2,0, "END" ,0.5*scale2,1.0*scale2,0,1,rgba(255,255,255,255))

					if myscreen.mouseclip=0 and vkey=0 then

							xcurold=1+((myscreen.mousex/scale2-x1/scale2-10)/24)
							ycurold=2+((-myscreen.mousey/scale2+y0/scale2+10)/25)

							if xcurold>0 then
							if xcurold<11 then
							if ycurold>0 then
							if ycurold<5 then

								if xcur<>xcurold or ycur<>ycurold then
									if _osgl_menumovesound<>0 then osgl_playsound(_osgl_menumovesound)
								end if

								xcur=xcurold
								ycur=ycurold

								mclip=0
							'osgl_print(x1+10+24*(xcur-1),y0+5+25*(ycur-1),0,"_",1.6,1.8,0,1,rgba(255,80-80*menusin,15,255))

						end if
						end if
						end if
						end if
					else
						'if multikey(&H48) then ycur-=1
						'if multikey(&H50) then ycur+=1
						'if multikey(&H4B) then xcur-=1
						'if multikey(&H4D) then xcur+=1
						xa=osgl_axis(_osgl_menuplayer,1)
						ya=osgl_axis(_osgl_menuplayer,2)
						if holdkey2=0 then
							if xa<-.5 then xcur-=1 : holdkey2=1
							if xa>.5 then xcur+=1 : holdkey2=1
							if ya<-.5 then ycur-=1 : holdkey2=1
							if ya>.5 then ycur+=1 : holdkey2=1
							if holdkey2 then
								if _osgl_menumovesound<>0 then osgl_playsound(_osgl_menumovesound)
							end if
							osgl_wrap(ycur,1,4)
							osgl_wrap(xcur,1,10)
						else
							if xa=0 and ya=0 then holdkey2=0 else myscreen.mouseinactive=_osgl_mousetimeout : myscreen.mouseclip=1
						end if

					end if

							if (osgl_mousebutton(1)=1 and mclip=0) or (osgl_button(_osgl_menuplayer)=1 and vkey=0) then


								if ycur=4 then
									select case xcur
										case 9: backspace=1
										case 10: enter=1
									end select
								end if

								if enter=0 then
								if backspace=0 then
									dim as string*1 mychar=lcase(virtkeyboard((ycur-1)*10+xcur))
									if right(outs,1)=" " or right(outs,1)="." or outs="" then mychar=ucase(mychar)
									outs=left(outs+mychar,numchars)
									if _osgl_menuclicksound<>0 then osgl_playsound(_osgl_menuclicksound)
								end if
								end if

							end if


						osgl_range(ycur,1,4)
						osgl_range(xcur,1,10)
					osgl_print(x1+(10+24*(xcur-1))*scale2,y0+(25*(ycur-1))*scale2,0,"_",1.6*scale2,1.7*scale2,0,1,rgba(255,80-80*menusin,15,255))

                    'osgl_print(x1+10,y0+5,0, "1 2 3 4 5 6 7 8 9 0",1.6,1.8,0,1,rgba(255,255,255,255))
                    'osgl_print(x1+10,y0+30,0,"A B C D E F G H I J",1.6,1.8,0,1,rgba(255,255,255,255))
                    'osgl_print(x1+10,y0+55,0,"K L M N O P Q R S T",1.6,1.8,0,1,rgba(255,255,255,255))
                    'osgl_print(x1+10,y0+80,0,"U V W X Y Z spc end",1.6,1.8,0,1,rgba(255,255,255,255))


                    osgl_drawborder(x1,y1,x2,y2,bordertype,0,1)

                    osgl_print(x1+10*scale2,y1+10*scale2,0,question,1.6*scale2,1.8*scale2,0,1,rgba(255,255,255,255))

                end if
                menuangle+=15
                if menuangle>359 then menuangle-=360
                menusin=sin(radians(menuangle))
                osgl_print(x1+80*scale2,y1+60*scale2,0,outs+"_",1.6*scale2,1.8*scale2,0,1,rgba(255,80-80*menusin,15,255))

				osgl_drawmouse

            else
                'osgl_syncbuffers
            end if

loop until getchoice<>0

if _osgl_menuclicksound<>0 then osgl_playsound(_osgl_menuclicksound)

            osgl_quad(    -myscreen.x/2,myscreen.y/2,_
            myscreen.x/2,-myscreen.y/2,_
            0,_
            screencapture,0,_
            0,0,_     'mirror,flip
            1,1,0,0,_   '        xrep,yrep,xscroll,yscroll,_
            7,0,_       '        blendmode,depthtest,_
            rgba(255,255,255,255))    '        r,g,b,a)

osgl_deletetexture(screencapture)

osgl_waitkeyrelease

_osgl_textboxoffset=offsetbak

osgl_playerinput(_osgl_menuplayer).usekeyboard=usekbdbak

function=outs
end function



Function osgl_detectwine() As Integer

        Dim As Any Ptr                          hDll
        Dim As Function() As Zstring Ptr        Wine_Get_Version
        Dim As Function() As Integer            GetDKrnl32Version

        Function = 0
        hDll = DyLibLoad( "ntdll.dll" )
        If( hDll )Then
                Wine_Get_Version = DyLibSymbol( hDll, "wine_get_version" )
                If( Wine_Get_Version )Then
                        Function = 1
                End If
                DyLibFree( hDll )
        End If

End Function


dim shared as string _osgl_execute_command, _osgl_execute_param

sub osgl_executecommandMT()
shell _osgl_execute_command
end sub

sub osgl_executecommand(comando as string)
_osgl_execute_command=comando
dim as any ptr i=@osgl_executecommandMT
threadcreate(i)
end sub

sub execMTinternal()
exec2(_osgl_execute_command,_osgl_execute_param)
'shell(exepath+"/lib32/rumble /dev/input/event8 0 1000")
end sub

sub execmt(comando as string, param as string)
_osgl_execute_command=comando
_osgl_execute_param=param
dim as any ptr i=@execMTinternal
threadcreate(i)
end sub


sub osgl_closeprogram(wname as string)
exec2("wmctrl","-c "+wname) 'linux only - needs wmctrl
end sub


'libjoyrumble.so
Dim shared joyrumble As Function (byval joynumber as integer=1, byval strong as integer=50, byval weak as integer=50, byval duration as integer=500) As Integer
#ifdef __FB_WIN32__
	libjoyrumble=dylibload(exepath+"/dll/libjoyrumble.dll")
#else
	libjoyrumble=dylibload(exepath+"/lib32/libjoyrumble.so")
	if libjoyrumble=0 then libjoyrumble=dylibload("/usr/lib/"+appname()+"/libjoyrumble.so")
	if libjoyrumble=0 then libjoyrumble=dylibload("/usr/lib/i386-linux-gnu/"+appname()+"/libjoyrumble.so")
	if libjoyrumble=0 then libjoyrumble=dylibload("/usr/lib32/"+appname()+"/libjoyrumble.so")
#endif
if libjoyrumble then
	printdebug "Input : libjoyrumble loaded :",libjoyrumble
end if
joyrumble=DyLibSymbol(libjoyrumble,"joyrumble")
if joyrumble<>0 then
	printdebug "Input : joyrumble function found : pointer :",joyrumble
else
	printdebug "Input : joyrumble function NOT found."
end if

sub osgl_joyrumble(byval joynumber as integer,byval strong as integer,byval weak as integer,byval duration as integer)
	if joynumber<1 then exit sub
	if joyrumble=0 or _osgl_joyrumble=0 or osgl_playerinput(joynumber).usegamepad=0 or osgl_playerinput(joynumber).hasff=0 then exit sub
	printdebug "Input : Rumble  P"+str(joynumber)
	joyrumble(osgl_playerinput(joynumber).usegamepad, strong, weak, duration)
end sub


#print "osgl compilation done."

'----------------------------------------------------------------------------------------------------------------------------end of osgl.bas

