# HG changeset patch # User Xeli # Date 1315538145 -7200 # Node ID 2e5835130d9ad8c17e21f4f3423dc2dcf7d19a81 # Parent 5ab22736bdb6eb79e0a4c59b9d08d06bccbed9b5# Parent f906f6645e02530b0dba7ed3de8ed8bf6389ea1a merge diff -r f906f6645e02 -r 2e5835130d9a .hgignore --- a/.hgignore Fri Sep 09 03:57:45 2011 +0200 +++ b/.hgignore Fri Sep 09 05:15:45 2011 +0200 @@ -36,3 +36,15 @@ glob:*.orig glob:*.bak glob:*.rej +glob:project_files/Android-build/SDL-android-project/jni/** +glob:project_files/Android-build/SDL-android-project/obj +glob:project_files/Android-build/SDL-android-project/libs +glob:project_files/Android-build/SDL-android-project/bin +glob:project_files/Android-build/SDL-android-project/gen +glob:project_files/Android-build/SDL-android-project/local.properties +glob:project_files/Android-build/SDL-android-project/default.properties +glob:project_files/Android-build/SDL-android-project/.* +glob:project_files/Android-build/complete_build.sh +glob:project_files/Android-build/pushToDevice.sh +glob:project_files/Android-build/Makefile.android +glob:project_files/Android-build/out diff -r f906f6645e02 -r 2e5835130d9a CMakeLists.txt --- a/CMakeLists.txt Fri Sep 09 03:57:45 2011 +0200 +++ b/CMakeLists.txt Fri Sep 09 05:15:45 2011 +0200 @@ -192,6 +192,9 @@ add_subdirectory(misc/liblua) add_subdirectory(hedgewars) +#Xeli: Should if/endif this one too? +add_subdirectory(project_files/Android-build) + if(NOT BUILD_ENGINE_LIBRARY) add_subdirectory(bin) add_subdirectory(misc/quazip) diff -r f906f6645e02 -r 2e5835130d9a hedgewars/PascalExports.pas --- a/hedgewars/PascalExports.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/PascalExports.pas Fri Sep 09 05:15:45 2011 +0200 @@ -32,6 +32,9 @@ {$INCLUDE "config.inc"} procedure HW_versionInfo(netProto: PLongInt; versionStr: PPChar); cdecl; export; +function HW_getNumberOfWeapons:LongInt; cdecl; export; +function HW_getMaxNumberOfTeams:LongInt; cdecl; export; +function HW_getMaxNumberOfHogs:LongInt; cdecl; export; implementation {$IFDEF HWLIBRARY} diff -r f906f6645e02 -r 2e5835130d9a hedgewars/SDLh.pas --- a/hedgewars/SDLh.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/SDLh.pas Fri Sep 09 05:15:45 2011 +0200 @@ -41,7 +41,9 @@ {$IFDEF HAIKU} {$linklib root} {$ELSE} - {$linklib pthread} + {$IFNDEF ANDROID} + {$linklib pthread} + {$ENDIF} {$ENDIF} {$ENDIF} @@ -81,11 +83,19 @@ SDL_ImageLibName = 'SDL_image'; SDL_NetLibName = 'SDL_net'; {$ELSE} - SDLLibName = 'libSDL.so'; - SDL_TTFLibName = 'libSDL_ttf.so'; - SDL_MixerLibName = 'libSDL_mixer.so'; - SDL_ImageLibName = 'libSDL_image.so'; - SDL_NetLibName = 'libSDL_net.so'; + {$IFDEF ANDROID} + SDLLibName = 'SDL'; + SDL_TTFLibName = 'libSDL_ttf.so'; + SDL_MixerLibName = 'libSDL_mixer.so'; + SDL_ImageLibName = 'libSDL_image.so'; + SDL_NetLibName = 'libSDL_net.so'; + {$ELSE} + SDLLibName = 'SDL'; + SDL_TTFLibName = 'libSDL_ttf.so'; + SDL_MixerLibName = 'libSDL_mixer.so'; + SDL_ImageLibName = 'libSDL_image.so'; + SDL_NetLibName = 'libSDL_net.so'; + {$ENDIF} {$ENDIF} {$ENDIF} @@ -136,6 +146,9 @@ SDL_JOYHATMOTION = $602; SDL_JOYBUTTONDOWN = $603; SDL_JOYBUTTONUP = $604; + SDL_FINGERDOWN = $700; + SDL_FINGERUP = $701; + SDL_FINGERMOTION = $702; //TODO: implement otheer event types SDL_USEREVENT = $8000; SDL_LASTEVENT = $FFFF; @@ -559,6 +572,19 @@ {$ENDIF} end; + SDL_TouchID = Int32; + SDL_FingerID = Int32; + + TSDL_TouchFingerEvent = record + type_: UInt32; + windowId: UInt32; + touchId: SDL_TouchID; + fingerId: SDL_FingerID; + state, padding1, padding2, padding3: UInt8; + x,y: UInt16; + dx,dy: Int16; + pressure: UInt16; + end; //TODO: implement SDL_TouchButtonEvent, SDL_MultiGestureEvent, SDL_DollarGestureEvent TSDL_QuitEvent = record @@ -595,6 +621,9 @@ SDL_JOYHATMOTION: (jhat: TSDL_JoyHatEvent); SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP: (jbutton: TSDL_JoyButtonEvent); + SDL_FINGERMOTION, + SDL_FINGERUP, + SDL_FINGERDOWN:(tfinger: TSDL_TouchFingerEvent); SDL_QUITEV: (quit: TSDL_QuitEvent); SDL_USEREVENT: (user: TSDL_UserEvent); //TODO: implement other events @@ -618,8 +647,10 @@ {$ENDIF} end; + TSDL_EventFilter = function( event : PSDL_Event ): Integer; cdecl; + PByteArray = ^TByteArray; TByteArray = array[0..65535] of Byte; PLongWordArray = ^TLongWordArray; @@ -799,6 +830,7 @@ function SDL_GetNumMice: LongInt; cdecl; external SDLLibName; function SDL_PixelFormatEnumToMasks(format: TSDL_ArrayByteOrder; bpp: PLongInt; Rmask, Gmask, Bmask, Amask: PLongInt): boolean; cdecl; external SDLLibName; + procedure SDL_WarpMouseInWindow(window: PSDL_Window; x, y: LongInt); cdecl; external SDLLibName; function SDL_SetHint(name, value: PChar): boolean; cdecl; external SDLLibName; @@ -821,6 +853,8 @@ procedure SDL_WM_SetCaption(title: PChar; icon: PChar); cdecl; external SDLLibName; function SDL_WM_ToggleFullScreen(surface: PSDL_Surface): LongInt; cdecl; external SDLLibName; +function SDL_CreateThread(fn: pointer; data: pointer): PSDL_Thread; cdecl; external SDLLibName; +procedure SDL_WaitThread(thread: PSDL_Thread; status: PLongInt); cdecl; external SDLLibName; function SDL_CreateMutex: PSDL_mutex; cdecl; external SDLLibName; procedure SDL_DestroyMutex(mutex: PSDL_mutex); cdecl; external SDLLibName; function SDL_LockMutex(mutex: PSDL_mutex): LongInt; cdecl; external SDLLibName name 'SDL_mutexP'; diff -r f906f6645e02 -r 2e5835130d9a hedgewars/hwLibrary.pas --- a/hedgewars/hwLibrary.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/hwLibrary.pas Fri Sep 09 05:15:45 2011 +0200 @@ -18,14 +18,45 @@ Library hwLibrary; +{$IFDEF fpc} +{$MODE delphi} +{$ENDIF} + +{$IFDEF ANDROID} + {$MACRO ON} + {$DEFINE Java_Prefix := 'Java_org_hedgewars_mobile_EngineProtocol_PascalExports_'} +{$ENDIF} + // Add all your Pascal units to the "uses" clause below to add them to the program. // Mark all Pascal procedures/functions that you wish to call from C/C++/Objective-C code using // "cdecl; export;" (see the fpclogo.pas unit for an example), and then add C-declarations for // these procedures/functions to the PascalImports.h file (also in the "Pascal Sources" group) // to make these functions available in the C/C++/Objective-C source files // (add "#include PascalImports.h" near the top of these files if it's not there yet) -uses PascalExports, hwengine; -exports Game, HW_versionInfo; +uses PascalExports, hwengine{$IFDEF ANDROID},jni{$ENDIF}; +exports Game{$IFNDEF ANDROID}, HW_versionInfo{$ENDIF}; + +function JNI_HW_versionInfoNet(env: PJNIEnv; obj: JObject):JInt;cdecl; +begin + JNI_HW_versionInfoNet := cNetProtoVersion; +end; + +function JNI_HW_versionInfoVersion(env: PJNIEnv; obj: JObject):JString; cdecl; +begin + JNI_HW_versionInfoVersion := env^.NewStringUTF(env, PChar(cVersionString)); +end; + + +{$IFDEF ANDROID} + exports + JNI_HW_versionInfoNet name Java_Prefix+'HWversionInfoNetProto', + JNI_HW_versionInfoVersion name Java_Prefix+'HWversionInfoVersion', + GenLandPreview name Java_Prefix + 'GenLandPreview', + HW_getNumberOfweapons name Java_Prefix + 'HWgetNumberOfWeapons', + HW_getMaxNumberOfHogs name Java_Prefix + 'HWgetMaxNumberOfHogs', + HW_getMaxNumberOfTeams name Java_Prefix + 'HWgetMaxNumberOfTeams'; +{$ENDIF} + begin end. diff -r f906f6645e02 -r 2e5835130d9a hedgewars/hwengine.pas --- a/hedgewars/hwengine.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/hwengine.pas Fri Sep 09 05:15:45 2011 +0200 @@ -31,12 +31,13 @@ uses SDLh, uMisc, uConsole, uGame, uConsts, uLand, uAmmos, uVisualGears, uGears, uStore, uWorld, uKeys, uSound, uScript, uTeams, uStats, uIO, uLocale, uChat, uAI, uAIMisc, uRandom, uLandTexture, uCollisions, - sysutils, uTypes, uVariables, uCommands, uUtils, uCaptions, uDebug, uCommandHandlers, uLandPainted; + sysutils, uTypes, uVariables, uCommands, uUtils, uCaptions, uDebug, uCommandHandlers, uLandPainted,uTouch {$IFDEF ANDROID}, GLUnit {$ENDIF}; {$IFDEF HWLIBRARY} procedure initEverything(complete:boolean); procedure freeEverything(complete:boolean); procedure Game(gameArgs: PPChar); cdecl; export; +procedure GenLandPreview(port: Longint); cdecl; export; implementation {$ELSE} @@ -167,6 +168,9 @@ cHasFocus:= true; onFocusStateChanged() end; + SDL_FINGERMOTION: onTouchMotion(event.tfinger.x, event.tfinger.y,event.tfinger.dx, event.tfinger.dy, event.tfinger.fingerId); + SDL_FINGERDOWN: onTouchDown(event.tfinger.x, event.tfinger.y, event.tfinger.fingerId); + SDL_FINGERUP: onTouchUp(event.tfinger.x, event.tfinger.y, event.tfinger.fingerId); {$ELSE} KeyPressChat(event.key.keysym.unicode); SDL_MOUSEBUTTONDOWN: if event.button.button = SDL_BUTTON_WHEELDOWN then wheelDown:= true; @@ -233,9 +237,14 @@ begin {$IFDEF HWLIBRARY} cBits:= 32; + cTimerInterval:= 8; +{$IFDEF ANDROID} + PathPrefix:= gameArgs[11]; + cFullScreen:= true; +{$ELSE} + PathPrefix:= 'Data'; cFullScreen:= false; - cTimerInterval:= 8; - PathPrefix:= 'Data'; +{$ENDIF} UserPathPrefix:= '.'; cShowFPS:= {$IFDEF DEBUGFILE}true{$ELSE}false{$ENDIF}; val(gameArgs[0], ipcPort); @@ -259,7 +268,6 @@ cOrigScreenHeight:= cScreenHeight; initEverything(true); - WriteLnToConsole('Hedgewars ' + cVersionString + ' engine (network protocol: ' + inttostr(cNetProtoVersion) + ')'); AddFileLog('Prefix: "' + PathPrefix +'"'); AddFileLog('UserPrefix: "' + UserPathPrefix +'"'); @@ -365,7 +373,11 @@ if complete then begin - uAI.initModule; +{$IFDEF ANDROID} + GLUnit.init; +{$ENDIF} + uTouch.initModule; + uAI.initModule; //uAIActions does not need initialization //uAIAmmoTests does not need initialization uAIMisc.initModule; diff -r f906f6645e02 -r 2e5835130d9a hedgewars/options.inc --- a/hedgewars/options.inc Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/options.inc Fri Sep 09 05:15:45 2011 +0200 @@ -27,16 +27,25 @@ {$DEFINE GLunit:=GL} +{$IFDEF ANDROID} + {$DEFINE SDL13} + {$DEFINE HWLIBRARY} + {$DEFINE S3D_DISABLED} + {$DEFINE GLunit:=gles11} + {$DEFINE DEBUGFILE} + {$DEFINE MOBILE} +{$ENDIF} + {$IFDEF IPHONEOS} {$DEFINE SDL13} {$DEFINE HWLIBRARY} {$DEFINE S3D_DISABLED} {$DEFINE GLunit:=gles11} -{$ELSE} - {$DEFINE DEBUGFILE} - //{$DEFINE TRACEAIACTIONS} - //{$DEFINE COUNTTICKS} + {$DEFINE MOBILE} {$ENDIF} +{$DEFINE DEBUGFILE} +//{$DEFINE TRACEAIACTIONS} +//{$DEFINE COUNTTICKS} //also available LUA_DISABLED diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uAI.pas --- a/hedgewars/uAI.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uAI.pas Fri Sep 09 05:15:45 2011 +0200 @@ -30,13 +30,13 @@ implementation uses uConsts, SDLh, uAIMisc, uAIAmmoTests, uAIActions, - uAmmos, SysUtils{$IFDEF UNIX}, cthreads{$ENDIF}, uTypes, - uVariables, uCommands, uUtils, uDebug; + uAmmos, SysUtils{$IFDEF UNIX}{$IFNDEF ANDROID}, cthreads{$ENDIF}{$ENDIF}, uTypes, + uVariables, uCommands, uUtils, uDebug, uConsole; var BestActions: TActions; CanUseAmmo: array [TAmmoType] of boolean; StopThinking: boolean; - ThinkThread: TThreadID; + ThinkThread: PSDL_Thread = nil; hasThread: LongInt; procedure FreeActionsList; @@ -74,8 +74,8 @@ with CurrentHedgehog^ do a:= CurAmmoType; aa:= a; - - ThreadSwitch(); +SDL_delay(0); +// ThreadSwitch(); repeat if (CanUseAmmo[a]) and @@ -265,9 +265,11 @@ if (PGear(Me)^.State and gstAttacked) = 0 then if Targets.Count > 0 then begin + WalkMe:= BackMe; Walk(@WalkMe); if (StartTicks > GameTicks - 1500) and not StopThinking then SDL_Delay(1000); + if BestActions.Score < -1023 then begin BestActions.Count:= 0; @@ -285,7 +287,9 @@ end; PGear(Me)^.State:= PGear(Me)^.State and not gstHHThinking; Think:= 0; -InterlockedDecrement(hasThread) + +InterlockedDecrement(hasThread); + end; procedure StartThink(Me: PGear); @@ -316,7 +320,9 @@ for a:= Low(TAmmoType) to High(TAmmoType) do CanUseAmmo[a]:= Assigned(AmmoTests[a].proc) and HHHasAmmo(Me^.Hedgehog^, a); AddFileLog('Enter Think Thread'); -BeginThread(@Think, Me, ThinkThread) +//BeginThread(@Think, Me, ThinkThread) +ThinkThread := SDL_CreateThread(@Think, Me); +AddFileLog('Thread started'); end; procedure ProcessBot; diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uCaptions.pas --- a/hedgewars/uCaptions.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uCaptions.pas Fri Sep 09 05:15:45 2011 +0200 @@ -59,7 +59,7 @@ grp: TCapGroup; offset: LongInt; begin -{$IFDEF IPHONEOS} +{$IFDEF MOBILE} offset:= 48; {$ELSE} offset:= 8; diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uCommandHandlers.pas diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uConsole.pas --- a/hedgewars/uConsole.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uConsole.pas Fri Sep 09 05:15:45 2011 +0200 @@ -26,9 +26,10 @@ procedure WriteToConsole(s: shortstring); procedure WriteLnToConsole(s: shortstring); function GetLastConsoleLine: shortstring; +function ShortStringAsPChar(s: shortstring): PChar; implementation -uses Types, uVariables, uUtils; +uses Types, uVariables, uUtils {$IFDEF ANDROID}, log in 'log.pas'{$ENDIF}; const cLineWidth: LongInt = 0; cLinesCount = 8; @@ -53,6 +54,9 @@ begin {$IFNDEF NOCONSOLE} AddFileLog('[Con] ' + s); +{$IFDEF ANDROID} + Log.__android_log_write(Log.Android_LOG_DEBUG, 'HW_Engine', ShortStringAsPChar('[Con]' + s)); +{$ELSE} Write(stderr, s); done:= false; @@ -70,18 +74,21 @@ done:= (Length(s) = 0); end; {$ENDIF} +{$ENDIF} end; procedure WriteLnToConsole(s: shortstring); begin {$IFNDEF NOCONSOLE} WriteToConsole(s); +{$IFNDEF ANDROID} WriteLn(stderr); inc(CurrLine); if CurrLine = cLinesCount then CurrLine:= 0; PByte(@ConsoleLines[CurrLine].s)^:= 0 {$ENDIF} +{$ENDIF} end; @@ -118,4 +125,12 @@ end; +Function ShortStringAsPChar(S: ShortString) : PChar; +Var NewString : String; +Begin +if Length(S) = High(S) then Dec(S[0]); +s[Ord(Length(s))+1] := #0; +Result := @S[1]; +End; + end. diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uConsts.pas --- a/hedgewars/uConsts.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uConsts.pas Fri Sep 09 05:15:45 2011 +0200 @@ -156,7 +156,7 @@ // do not change this value cDefaultZoomLevel = 2.0; -{$IFDEF IPHONEOS} +{$IFDEF MOBILE} cMaxZoomLevel = 0.5; cMinZoomLevel = 3.5; cZoomDelta = 0.20; @@ -166,6 +166,8 @@ cZoomDelta = 0.25; {$ENDIF} + cMinMaxZoomLevelDelta = cMaxZoomLevel - cMinZoomLevel; + cSendEmptyPacketTime = 1000; trigTurns = $80000001; diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uFloat.pas --- a/hedgewars/uFloat.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uFloat.pas Fri Sep 09 05:15:45 2011 +0200 @@ -62,6 +62,7 @@ // The implemented operators +operator = (const z1, z2: hwFloat) z:boolean; inline; operator + (const z1, z2: hwFloat) z : hwFloat; inline; operator - (const z1, z2: hwFloat) z : hwFloat; inline; operator - (const z1: hwFloat) z : hwFloat; inline; @@ -88,7 +89,7 @@ function AngleCos(const Angle: Longword): hwFloat; function SignAs(const num, signum: hwFloat): hwFloat; inline; // Returns an hwFloat with the value of parameter num and the sign of signum. function hwSign(r: hwFloat): LongInt; inline; // Returns an integer with value 1 and sign of parameter r. - +function isZero(const z: hwFloat): boolean; inline; {$IFDEF FPC} {$J-} {$ENDIF} @@ -158,10 +159,13 @@ _40: hwFloat = (isNegative: false; QWordValue: 4294967296 * 40); _50: hwFloat = (isNegative: false; QWordValue: 4294967296 * 50); _70: hwFloat = (isNegative: false; QWordValue: 4294967296 * 70); + _90: hwFloat = (isNegative: false; QWordValue: 4294967296 * 90); _128: hwFloat = (isNegative: false; QWordValue: 4294967296 * 128); + _180: hwFloat = (isNegative: false; QWordValue: 4294967296 * 180); _250: hwFloat = (isNegative: false; QWordValue: 4294967296 * 250); _256: hwFloat = (isNegative: false; QWordValue: 4294967296 * 256); _300: hwFloat = (isNegative: false; QWordValue: 4294967296 * 300); + _360: hwFloat = (isNegative: false; QWordValue: 4294967296 * 360); _450: hwFloat = (isNegative: false; QWordValue: 4294967296 * 450); _1000: hwFloat = (isNegative: false; QWordValue: 4294967296 * 1000); _1024: hwFloat = (isNegative: false; QWordValue: 4294967296 * 1024); @@ -197,6 +201,12 @@ if i.isNegative then hwFloat2Float:= -hwFloat2Float; end; +operator = (const z1, z2: hwFloat) z:boolean; inline; +begin + z:= (z1.isNegative = z2.isNegative) and (z1.QWordValue = z2.QWordValue); +end; + + operator + (const z1, z2: hwFloat) z : hwFloat; begin if z1.isNegative = z2.isNegative then @@ -403,6 +413,10 @@ else AngleCos.QWordValue:= SinTable[Angle - 1024] end; +function isZero(const z: hwFloat): boolean; inline; +begin + isZero := z.QWordValue = 0; +end; {$ENDIF} end. diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uGame.pas --- a/hedgewars/uGame.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uGame.pas Fri Sep 09 05:15:45 2011 +0200 @@ -26,7 +26,7 @@ //////////////////// implementation //////////////////// -uses uKeys, uTeams, uIO, uAI, uGears, uSound, uMobile, uVisualGears, uTypes, uVariables; +uses uKeys, uTeams, uIO, uAI, uGears, uSound, uMobile, uVisualGears, uTypes, uVariables, uTouch; procedure DoGameTick(Lag: LongInt); var i: LongInt; @@ -52,7 +52,8 @@ if not CurrentTeam^.ExtDriven then begin if CurrentHedgehog^.BotLevel <> 0 then ProcessBot; - ProcessGears + ProcessGears; + ProcessTouch; end else begin NetGetNextCmd; diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uGearsRender.pas --- a/hedgewars/uGearsRender.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uGearsRender.pas Fri Sep 09 05:15:45 2011 +0200 @@ -188,7 +188,7 @@ procedure DrawHH(Gear: PGear; ox, oy: LongInt); var i, t: LongInt; amt: TAmmoType; - sign, hx, hy, cx, cy, tx, ty, sx, sy, m: LongInt; // hedgehog, crosshair, temp, sprite, direction + sign, hx, hy, tx, ty, sx, sy, m: LongInt; // hedgehog, crosshair, temp, sprite, direction dx, dy, ax, ay, aAngle, dAngle, hAngle, lx, ly: real; // laser, change defaultPos, HatVisible: boolean; HH: PHedgehog; @@ -319,10 +319,12 @@ end; end; // draw crosshair - cx:= Round(hwRound(Gear^.X) + dx * 80 + GetLaunchX(HH^.CurAmmoType, sign * m, Gear^.Angle)); - cy:= Round(hwRound(Gear^.Y) + dy * 80 + GetLaunchY(HH^.CurAmmoType, Gear^.Angle)); + CrosshairX := Round(hwRound(Gear^.X) + dx * 80 + GetLaunchX(HH^.CurAmmoType, sign * m, Gear^.Angle)); + CrosshairY := Round(hwRound(Gear^.Y) + dy * 80 + GetLaunchY(HH^.CurAmmoType, Gear^.Angle)); + + DrawRotatedTex(HH^.Team^.CrosshairTex, - 12, 12, cx + WorldDx, cy + WorldDy, 0, + 12, 12, CrosshairX + WorldDx, CrosshairY + WorldDy, 0, sign * (Gear^.Angle * 180.0) / cMaxAngle); end; hx:= ox + 8 * sign; diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uLand.pas --- a/hedgewars/uLand.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uLand.pas Fri Sep 09 05:15:45 2011 +0200 @@ -1414,7 +1414,7 @@ if digest = '' then digest:= s else - TryDo(s = digest, 'Different maps generated, sorry', true); +// TryDo(s = digest, 'Different maps generated, sorry', true); end; procedure chSendLandDigest(var s: shortstring); diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uScript.pas --- a/hedgewars/uScript.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uScript.pas Fri Sep 09 05:15:45 2011 +0200 @@ -44,6 +44,9 @@ function ScriptCall(fname : shortstring; par1, par2, par3, par4 : LongInt) : LongInt; function ScriptExists(fname : shortstring) : boolean; + +function ParseCommandOverride(key, value : shortstring) : shortstring; + procedure initModule; procedure freeModule; @@ -1677,6 +1680,25 @@ GetGlobals; end; +function ParseCommandOverride(key, value : shortstring) : shortstring; +begin +ParseCommandOverride:= value; +if not ScriptExists('ParseCommandOverride') then exit; +lua_getglobal(luaState, Str2PChar('ParseCommandOverride')); +lua_pushstring(luaState, Str2PChar(key)); +lua_pushstring(luaState, Str2PChar(value)); +if lua_pcall(luaState, 2, 1, 0) <> 0 then + begin + LuaError('Lua: Error while calling ParseCommandOverride: ' + lua_tostring(luaState, -1)); + lua_pop(luaState, 1) + end +else + begin + ParseCommandOverride:= lua_tostring(luaState, -1); + lua_pop(luaState, 1) + end; +end; + function ScriptCall(fname : shortstring; par1: LongInt) : LongInt; begin ScriptCall:= ScriptCall(fname, par1, 0, 0, 0) @@ -2029,6 +2051,11 @@ ScriptExists:= false end; +function ParseCommandOverride(key, value : shortstring) : shortstring; +begin +ParseCommandOverride:= value +end; + procedure initModule; begin end; diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uSound.pas --- a/hedgewars/uSound.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uSound.pas Fri Sep 09 05:15:45 2011 +0200 @@ -148,7 +148,7 @@ WriteToConsole('Init sound...'); isSoundEnabled:= SDL_InitSubSystem(SDL_INIT_AUDIO) >= 0; -{$IFDEF IPHONEOS} +{$IFDEF MOBILE} channels:= 1; {$ELSE} channels:= 2; diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uStore.pas --- a/hedgewars/uStore.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uStore.pas Fri Sep 09 05:15:45 2011 +0200 @@ -998,7 +998,7 @@ y:= SDL_WINDOWPOS_CENTERED_MASK; flags:= SDL_WINDOW_OPENGL or SDL_WINDOW_SHOWN; -{$IFDEF IPHONEOS} +{$IFDEF MOBILE} // make the sdl window appear on the second monitor when present x:= x or (SDL_GetNumVideoDisplays() - 1); y:= y or (SDL_GetNumVideoDisplays() - 1); diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uTouch.pas --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/hedgewars/uTouch.pas Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,484 @@ +(* + * Hedgewars, a free turn based strategy game + * Copyright (c) 2011 Richard Deurwaarder + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + *) + +{$INCLUDE "options.inc"} + +unit uTouch; + +interface + +uses sysutils, math, uConsole, uVariables, SDLh, uTypes, uFloat, uConsts, uIO, uCommands, GLUnit, uCommandHandlers; + +type + PTouch_Finger = ^Touch_Finger; + Touch_Finger = record + id : SDL_FingerId; + x,y : LongInt; + historicalX, historicalY : LongInt; + timeSinceDown : Longword; + end; + +procedure initModule; + +procedure ProcessTouch; +procedure onTouchDown(x,y: Longword; pointerId: SDL_FingerId); +procedure onTouchMotion(x,y: Longword; dx,dy: LongInt; pointerId: SDL_FingerId); +procedure onTouchUp(x,y: Longword; pointerId: SDL_FingerId); +function convertToCursor(scale: LongInt; xy: LongInt): LongInt; +function addFinger(x,y: Longword; id: SDL_FingerId): PTouch_Finger; +procedure deleteFinger(id: SDL_FingerId); +procedure onTouchClick(finger: Touch_Finger); +procedure onTouchDoubleClick(finger: Touch_Finger); + +function findFinger(id: SDL_FingerId): PTouch_Finger; +procedure aim(finger: Touch_Finger); +function isOnCrosshair(finger: Touch_Finger): boolean; +function isOnCurrentHog(finger: Touch_Finger): boolean; +function isOnFireButton(finger: Touch_Finger): boolean; +procedure convertToWorldCoord(var x,y: hwFloat; finger: Touch_Finger); +function fingerHasMoved(finger: Touch_Finger): boolean; +function calculateDelta(finger1, finger2: Touch_Finger): hwFloat; +function getSecondFinger(finger: Touch_Finger): PTouch_Finger; +procedure printFinger(finger: Touch_Finger); +implementation + +const + clicktime = 200; + nilFingerId = High(SDL_FingerId); +var + leftButtonBoundary : LongInt; + rightButtonBoundary : LongInt; + topButtonBoundary : LongInt; + + pointerCount : Longword; + fingers: array of Touch_Finger; + moveCursor : boolean; + invertCursor : boolean; + + xTouchClick,yTouchClick : LongInt; + timeSinceClick : Longword; + + //Pinch to zoom + pinchSize : hwFloat; + baseZoomValue: GLFloat; + + + //aiming + aiming, movingCrosshair: boolean; + crosshairCommand: ShortString; + targetAngle: LongInt; + stopFiring: boolean; + + //moving + stopLeft, stopRight, walkingLeft, walkingRight : boolean; + + +procedure onTouchDown(x,y: Longword; pointerId: SDL_FingerId); +var + finger: PTouch_Finger; +begin + finger := addFinger(x,y,pointerId); + case pointerCount of + 1: + begin + moveCursor:= false; + if bShowAmmoMenu then + begin + moveCursor := true; + exit; + end; + + if isOnCrosshair(finger^) then + begin + aiming:= true; + exit; + end; + + if isOnFireButton(finger^) then + begin + stopFiring:= false; + ParseCommand('+attack', true); + exit; + end; + if (finger^.x < leftButtonBoundary) and (finger^.y < 390) then + begin + ParseCommand('+left', true); + walkingLeft := true; + exit; + end; + if finger^.x > rightButtonBoundary then + begin + ParseCommand('+right', true); + walkingRight:= true; + exit; + end; + if finger^.y < topButtonBoundary then + begin + ParseCommand('hjump', true); + exit; + end; + moveCursor:= true; + end; + 2: + begin + aiming:= false; + stopFiring:= true; + pinchSize := calculateDelta(finger^, getSecondFinger(finger^)^); + baseZoomValue := ZoomValue + end; + end;//end case pointerCount of +end; + +procedure onTouchMotion(x,y: Longword;dx,dy: LongInt; pointerId: SDL_FingerId); +var + finger, secondFinger: PTouch_Finger; + currentPinchDelta, zoom : hwFloat; +begin + finger:= findFinger(pointerId); + + finger^.x := convertToCursor(cScreenWidth, x); + finger^.y := convertToCursor(cScreenHeight, y); + + case pointerCount of + 1: + begin + if aiming then + begin + aim(finger^); + exit + end; + if moveCursor then + if invertCursor then + begin + CursorPoint.X := CursorPoint.X - convertToCursor(cScreenWidth,dx); + CursorPoint.Y := CursorPoint.Y + convertToCursor(cScreenWidth,dy); + end + else + begin + CursorPoint.X := CursorPoint.X + convertToCursor(cScreenWidth,dx); + CursorPoint.Y := CursorPoint.Y - convertToCursor(cScreenWidth,dy); + end; + end; + 2: + begin + secondFinger := getSecondFinger(finger^); + currentPinchDelta := calculateDelta(finger^, secondFinger^) - pinchSize; + zoom := currentPinchDelta/cScreenWidth; + ZoomValue := baseZoomValue - ((hwFloat2Float(zoom) * cMinMaxZoomLevelDelta)); + if ZoomValue < cMaxZoomLevel then ZoomValue := cMaxZoomLevel; + if ZoomValue > cMinZoomLevel then ZoomValue := cMinZoomLevel; + end; + end; //end case pointerCount of +end; + +procedure onTouchUp(x,y: Longword; pointerId: SDL_FingerId); +begin + aiming:= false; + stopFiring:= true; + deleteFinger(pointerId); + + if walkingLeft then + begin + ParseCommand('-left', true); + walkingLeft := false; + end; + + if walkingRight then + begin + ParseCommand('-right', true); + walkingRight := false; + end; +end; + +procedure onTouchDoubleClick(finger: Touch_Finger); +begin + ParseCommand('ljump', true); +end; + +procedure onTouchClick(finger: Touch_Finger); +begin + if (SDL_GetTicks - timeSinceClick < 300) and (DistanceI(finger.X-xTouchClick, finger.Y-yTouchClick) < _30) then + begin + onTouchDoubleClick(finger); + exit; + end + else + begin + xTouchClick := finger.x; + yTouchClick := finger.y; + timeSinceClick := SDL_GetTicks; + end; + + if bShowAmmoMenu then + begin + doPut(CursorPoint.X, CursorPoint.Y, false); + exit + end; + + if isOnCurrentHog(finger) then + begin + bShowAmmoMenu := true; + exit; + end; + + if finger.y < topButtonBoundary then + begin + ParseCommand('hjump', true); + exit; + end; +end; + +function addFinger(x,y: Longword; id: SDL_FingerId): PTouch_Finger; +var + xCursor, yCursor, index : LongInt; +begin + //Check array sizes + if length(fingers) < pointerCount then + begin + setLength(fingers, length(fingers)*2); + for index := length(fingers) div 2 to length(fingers) do fingers[index].id := nilFingerId; + end; + + + xCursor := convertToCursor(cScreenWidth, x); + yCursor := convertToCursor(cScreenHeight, y); + + //on removing fingers, all fingers are moved to the left + //with dynamic arrays being zero based, the new position of the finger is the old pointerCount + fingers[pointerCount].id := id; + fingers[pointerCount].historicalX := xCursor; + fingers[pointerCount].historicalY := yCursor; + fingers[pointerCount].x := xCursor; + fingers[pointerCount].y := yCursor; + fingers[pointerCount].timeSinceDown:= SDL_GetTicks; + + addFinger:= @fingers[pointerCount]; + inc(pointerCount); +end; + +procedure deleteFinger(id: SDL_FingerId); +var + index : Longint; +begin + + dec(pointerCount); + for index := 0 to pointerCount do + begin + if fingers[index].id = id then + begin + //Check for onTouchClick event + if ((SDL_GetTicks - fingers[index].timeSinceDown) < clickTime) AND + not(fingerHasMoved(fingers[index])) then onTouchClick(fingers[index]); + + //put the last finger into the spot of the finger to be removed, + //so that all fingers are packed to the far left + if pointerCount <> index then + begin + fingers[index].id := fingers[pointerCount].id; + fingers[index].x := fingers[pointerCount].x; + fingers[index].y := fingers[pointerCount].y; + fingers[index].historicalX := fingers[pointerCount].historicalX; + fingers[index].historicalY := fingers[pointerCount].historicalY; + fingers[index].timeSinceDown := fingers[pointerCount].timeSinceDown; + + fingers[pointerCount].id := nilFingerId; + end + else fingers[index].id := nilFingerId; + break; + end; + end; + +end; + +procedure ProcessTouch; +var + deltaAngle: LongInt; +begin + invertCursor := not(bShowAmmoMenu); + if aiming then + begin + if CurrentHedgehog^.Gear <> nil then + begin + deltaAngle:= CurrentHedgehog^.Gear^.Angle - targetAngle; + if (deltaAngle <> 0) and not(movingCrosshair) then + begin + ParseCommand('+' + crosshairCommand, true); + movingCrosshair := true; + end + else + if movingCrosshair then + begin + ParseCommand('-' + crosshairCommand, true); + movingCrosshair:= false; + end; + end; + end + else if movingCrosshair then + begin + ParseCommand('-' + crosshairCommand, true); + movingCrosshair := false; + end; + + if stopFiring then + begin + ParseCommand('-attack', true); + stopFiring:= false; + end; + + if stopRight then + begin + stopRight := false; + ParseCommand('-right', true); + end; + + if stopLeft then + begin + stopLeft := false; + ParseCommand('-left', true); + end; + +end; + +function findFinger(id: SDL_FingerId): PTouch_Finger; +var + index: LongWord; +begin + for index := 0 to High(fingers) do + if fingers[index].id = id then + begin + findFinger := @fingers[index]; + break; + end; +end; + +procedure aim(finger: Touch_Finger); +var + hogX, hogY, touchX, touchY, deltaX, deltaY, tmpAngle: hwFloat; + tmp: ShortString; +begin + if CurrentHedgehog^.Gear <> nil then + begin + hogX := CurrentHedgehog^.Gear^.X; + hogY := CurrentHedgehog^.Gear^.Y; + + convertToWorldCoord(touchX, touchY, finger); + deltaX := hwAbs(TouchX-HogX); + deltaY := (TouchY-HogY); + + tmpAngle:= DeltaY / Distance(deltaX, deltaY) *_2048; + targetAngle:= (hwRound(tmpAngle) + 2048) div 2; + + tmp := crosshairCommand; + if CurrentHedgehog^.Gear^.Angle - targetAngle < 0 then crosshairCommand := 'down' + else crosshairCommand:= 'up'; + if movingCrosshair and (tmp <> crosshairCommand) then + begin + ParseCommand('-' + tmp, true); + movingCrosshair := false; + end; + + end; //if CurrentHedgehog^.Gear <> nil +end; + +function convertToCursor(scale: LongInt; xy: LongInt): LongInt; +begin + convertToCursor := round(xy/32768*scale) +end; + +function isOnFireButton(finger: Touch_Finger): boolean; +begin + printFinger(finger); + WriteToConsole(Format('%d %d ',[round((-cScreenWidth+20)/0.8), round((cScreenHeight+55)/0.8)])); + WriteToConsole(Format('%d, %d',[cScreenWidth, cScreenHeight])); + isOnFireButton:= (finger.x < 205) and (finger.y > 420); +end; + +function isOnCrosshair(finger: Touch_Finger): boolean; +var + x,y,fingerX, fingerY : hwFloat; +begin + x := int2hwFloat(CrosshairX); + y := int2hwFloat(CrosshairY); + + convertToWorldCoord(fingerX, fingerY, finger); + isOnCrosshair:= Distance(fingerX-x, fingerY-y) < _20; +end; + +function isOnCurrentHog(finger: Touch_Finger): boolean; +var + x,y, fingerX, fingerY : hwFloat; +begin + x := CurrentHedgehog^.Gear^.X; + y := CurrentHedgehog^.Gear^.Y; + + convertToWorldCoord(fingerX, fingerY, finger); + isOnCurrentHog := Distance(fingerX-x, fingerY-y) < _20; +end; + +procedure convertToWorldCoord(var x,y: hwFloat; finger: Touch_Finger); +begin +//if x <> nil then + x := int2hwFloat((finger.x-WorldDx) - (cScreenWidth div 2)); +//if y <> nil then + y := int2hwFloat(finger.y-WorldDy); +end; + +//Method to calculate the distance this finger has moved since the downEvent +function fingerHasMoved(finger: Touch_Finger): boolean; +begin + fingerHasMoved := trunc(sqrt(Power(finger.X-finger.historicalX,2) + Power(finger.y-finger.historicalY, 2))) > 330; +end; + +function calculateDelta(finger1, finger2: Touch_Finger): hwFloat; inline; +begin + calculateDelta := DistanceI(finger2.x-finger1.x, finger2.y-finger1.y); +end; + +// Under the premise that all pointer ids in pointerIds:SDL_FingerId are packed to the far left. +// If the pointer to be ignored is not pointerIds[0] the second must be there +function getSecondFinger(finger: Touch_Finger): PTouch_Finger; +begin + if fingers[0].id = finger.id then getSecondFinger := @fingers[1] + else getSecondFinger := @fingers[0]; +end; + +procedure printFinger(finger: Touch_Finger); +begin + WriteToConsole(Format('id:%d, (%d,%d), (%d,%d), time: %d', [finger.id, finger.x, finger.y, finger.historicalX, finger.historicalY, finger.timeSinceDown])); +end; + +procedure initModule; +var + index: Longword; +begin + movingCrosshair := false; + stopFiring:= false; + walkingLeft := false; + walkingRight := false; + + leftButtonBoundary := cScreenWidth div 4; + rightButtonBoundary := cScreenWidth div 4*3; + topButtonBoundary := cScreenHeight div 6; + + setLength(fingers, 4); + for index := 0 to High(fingers) do + fingers[index].id := nilFingerId; +end; + +begin +end. diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uTypes.pas --- a/hedgewars/uTypes.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uTypes.pas Fri Sep 09 05:15:45 2011 +0200 @@ -44,7 +44,7 @@ // Different files are stored in different folders, this enumeration is used to tell which folder to use TPathType = (ptNone, ptData, ptGraphics, ptThemes, ptCurrTheme, ptTeams, ptMaps, ptMapCurrent, ptDemos, ptSounds, ptGraves, ptFonts, ptForts, - ptLocale, ptAmmoMenu, ptHedgehog, ptVoices, ptHats, ptFlags, ptMissionMaps, ptSuddenDeath); + ptLocale, ptAmmoMenu, ptHedgehog, ptVoices, ptHats, ptFlags, ptMissionMaps, ptSuddenDeath, ptButtons); // Available sprites for displaying stuff TSprite = (sprWater, sprCloud, sprBomb, sprBigDigit, sprFrame, @@ -82,7 +82,7 @@ sprSMineOff, sprSMineOn, sprHandSMine, sprHammer, sprHandResurrector, sprCross, sprAirDrill, sprNapalmBomb, sprBulletHit, sprSnowball, sprHandSnowball, sprSnow, - sprSDFlake, sprSDWater, sprSDCloud, sprSDSplash, sprSDDroplet, sprTardis + sprSDFlake, sprSDWater, sprSDCloud, sprSDSplash, sprSDDroplet, sprTardis, sprFireButton ); // Gears that interact with other Gears and/or Land @@ -152,7 +152,7 @@ // Different kind of crates that e.g. hedgehogs can pick up TCrateType = (HealthCrate, AmmoCrate, UtilityCrate); - THWFont = (fnt16, fntBig, fntSmall {$IFNDEF IPHONEOS}, CJKfnt16, CJKfntBig, CJKfntSmall{$ENDIF}); + THWFont = (fnt16, fntBig, fntSmall {$IFNDEF MOBILE}, CJKfnt16, CJKfntBig, CJKfntSmall{$ENDIF}); TCapGroup = (capgrpGameState, capgrpAmmoinfo, capgrpVolume, capgrpMessage, capgrpMessage2, capgrpAmmostate); diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uUtils.pas --- a/hedgewars/uUtils.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uUtils.pas Fri Sep 09 05:15:45 2011 +0200 @@ -274,7 +274,7 @@ tmpstr: array[0..256] of WideChar; begin -{$IFNDEF IPHONEOS} +{$IFNDEF MOBILE} // remove chinese fonts for now if (font >= CJKfnt16) or (length(s) = 0) then {$ENDIF} @@ -333,12 +333,13 @@ end; procedure initModule; -{$IFDEF DEBUGFILE}{$IFNDEF IPHONEOS}var i: LongInt;{$ENDIF}{$ENDIF} +{$IFDEF DEBUGFILE}{$IFNDEF MOBILE}var i: LongInt;{$ENDIF}{$ENDIF} begin {$IFDEF DEBUGFILE} {$I-} -{$IFDEF IPHONEOS} - Assign(f,'../Documents/hw-' + cLogfileBase + '.log'); +{$IFDEF MOBILE} + {$IFDEF IPHONEOS} Assign(f,'../Documents/hw-' + cLogfileBase + '.log'); {$ENDIF} + {$IFDEF ANDROID} Assign(f,pathPrefix + '/' + cLogfileBase + '.log'); {$ENDIF} Rewrite(f); {$ELSE} if (ParamStr(1) <> '') and (ParamStr(2) <> '') then diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uVariables.pas --- a/hedgewars/uVariables.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uVariables.pas Fri Sep 09 05:15:45 2011 +0200 @@ -135,6 +135,8 @@ bWaterRising : boolean; //ShowCrosshair : boolean; This variable is inconvenient to set. Easier to decide when rendering + CrosshairX : LongInt; + CrosshairY : LongInt; CursorMovementX : LongInt; CursorMovementY : LongInt; cDrownSpeed : hwFloat; @@ -211,7 +213,8 @@ 'Graphics/Hats', // ptHats 'Graphics/Flags', // ptFlags 'Missions/Maps', // ptMissionMaps - 'Graphics/SuddenDeath' // ptSuddenDeath + 'Graphics/SuddenDeath', // ptSuddenDeath + 'Graphics/Buttons' // ptButton ); cTagsMasks : array[0..15] of byte = (7, 0, 0, 0, 15, 6, 4, 5, 0, 0, 0, 0, 0, 14, 12, 13); @@ -241,7 +244,7 @@ Height: 10; style: TTF_STYLE_NORMAL; Name: 'DejaVuSans-Bold.ttf') - {$IFNDEF IPHONEOS}, // remove chinese fonts for now + {$IFNDEF MOBILE}, // remove chinese fonts for now (Handle: nil; Height: 12; style: TTF_STYLE_NORMAL; @@ -618,8 +621,10 @@ Width: 80; Height: 50; imageWidth: 0; imageHeight: 0; saveSurf: false; priority: tpMedium; getDimensions: false; getImageDimensions: true),// sprSDSplash (FileName: 'SDDroplet'; Path: ptCurrTheme; AltPath: ptSuddenDeath; Texture: nil; Surface: nil; Width: 16; Height: 16; imageWidth: 0; imageHeight: 0; saveSurf: false; priority: tpHighest; getDimensions: false; getImageDimensions: true),// sprSDDroplet - (FileName: 'TARDIS'; Path: ptGraphics; AltPath: ptNone; Texture: nil; Surface: nil; - Width: 48; Height: 79; imageWidth: 0; imageHeight: 0; saveSurf: false; priority: tpHighest; getDimensions: false; getImageDimensions: true)// sprTardis + (FileName: 'Egg'; Path: ptGraphics; AltPath: ptNone; Texture: nil; Surface: nil;//TODO change back 'Egg' to 'Tardis' + Width: 0; Height: 0; imageWidth: 0; imageHeight: 0; saveSurf: false; priority: tpMedium; getDimensions: true; getImageDimensions: true),// sprTardis + (FileName: 'firebutton'; Path: ptButtons; AltPath: ptNone; Texture: nil; Surface: nil; + Width: 450; Height: 150; imageWidth: 0; imageHeight: 0; saveSurf: false; priority: tpHigh; getDimensions: false; getImageDimensions: true) // sprFireButton ); @@ -757,7 +762,7 @@ (FileName: 'bump.ogg'; Path: ptSounds),// sndBump (FileName: 'hogchant3.ogg'; Path: ptSounds),// sndResurrector (FileName: 'plane.ogg'; Path: ptSounds), // sndPlane - (FileName: 'TARDIS.ogg'; Path: ptSounds) // sndTardis + (FileName: 'plane.ogg'; Path: ptSounds) // sndTardis TODO change when using a new data set ); Ammoz: array [TAmmoType] of record diff -r f906f6645e02 -r 2e5835130d9a hedgewars/uWorld.pas --- a/hedgewars/uWorld.pas Fri Sep 09 03:57:45 2011 +0200 +++ b/hedgewars/uWorld.pas Fri Sep 09 05:15:45 2011 +0200 @@ -183,7 +183,7 @@ WorldDx:= - (LAND_WIDTH div 2) + cScreenWidth div 2; WorldDy:= - (LAND_HEIGHT - (playHeight div 2)) + (cScreenHeight div 2); AMSlotSize:= 33; -{$IFDEF IPHONEOS} +{$IFDEF MOBILE} AMxOffset:= 10; AMyOffset:= 10 + 123; // moved downwards AMWidth:= (cMaxSlotAmmoIndex + 1) * AMSlotSize + AMxOffset; @@ -252,7 +252,7 @@ SlotsNum:= 0; x:= (cScreenWidth shr 1) - AMWidth + AMxShift; -{$IFDEF IPHONEOS} +{$IFDEF MOBILE} Slot:= cMaxSlotIndex; x:= x - cOffsetY; y:= AMyOffset; @@ -376,7 +376,7 @@ RenderWeaponTooltip(amSel) end; -{$IFDEF IPHONEOS} +{$IFDEF MOBILE} DrawTexture(cScreenWidth div 2 - (AMWidth - 10) + AMxShift, AMyOffset - 25, Ammoz[Ammo^[Slot, Pos].AmmoType].NameTex); if Ammo^[Slot, Pos].Count < AMMO_INFINITE then @@ -400,7 +400,7 @@ else FreeWeaponTooltip; if (WeaponTooltipTex <> nil) and (AMxShift = 0) then -{$IFDEF IPHONEOS} +{$IFDEF MOBILE} ShowWeaponTooltip(x - WeaponTooltipTex^.w - 3, AMyOffset - 1); {$ELSE} ShowWeaponTooltip(x - WeaponTooltipTex^.w - 3, Min(y + 1, cScreenHeight - WeaponTooltipTex^.h - 40)); @@ -884,7 +884,7 @@ SetScale(cDefaultZoomLevel); // Turn time -{$IFDEF IPHONEOS} +{$IFDEF MOBILE} offsetX:= cScreenHeight - 13; {$ELSE} offsetX:= 48; @@ -913,6 +913,11 @@ // Captions DrawCaptions; +// Draw buttons +SetScale(0.8); +DrawSprite(sprFireButton, round((-cScreenWidth+20)/0.8),round((cScreenHeight+55)/0.8),0); +SetScale(cDefaultZoomLevel); + // Teams Healths if TeamsCount * 20 > cScreenHeight div 7 then // take up less screen on small displays begin @@ -986,7 +991,7 @@ if isInLag then DrawSprite(sprLag, 32 - (cScreenWidth shr 1), 32, (RealTicks shr 7) mod 12); // Wind bar -{$IFDEF IPHONEOS} +{$IFDEF MOBILE} offsetX:= cScreenHeight - 13; offsetY:= (cScreenWidth shr 1) + 74; {$ELSE} @@ -1038,7 +1043,7 @@ end; // fps -{$IFDEF IPHONEOS} +{$IFDEF MOBILE} offsetX:= 8; {$ELSE} offsetX:= 10; @@ -1181,7 +1186,7 @@ var EdgesDist, wdy, shs: LongInt; PrevSentPointTime: LongWord = 0; begin -{$IFNDEF IPHONEOS} +{$IFNDEF MOBILE} if (not (CurrentTeam^.ExtDriven and isCursorVisible and not bShowAmmoMenu)) and cHasFocus and (GameState <> gsConfirm) then uCursor.updatePosition(); {$ENDIF} @@ -1206,7 +1211,7 @@ if AMxShift < AMWidth then begin -{$IFDEF IPHONEOS} +{$IFDEF MOBILE} if CursorPoint.X < cScreenWidth div 2 + AMxShift - AMWidth then CursorPoint.X:= cScreenWidth div 2 + AMxShift - AMWidth; if CursorPoint.X > cScreenWidth div 2 + AMxShift - AMxOffset then CursorPoint.X:= cScreenWidth div 2 + AMxShift - AMxOffset; if CursorPoint.Y < cScreenHeight - AMyOffset - SlotsNum * AMSlotSize then CursorPoint.Y:= cScreenHeight - AMyOffset - SlotsNum * AMSlotSize; diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/CMakeLists.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/CMakeLists.txt Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,121 @@ +################################################################################### +# Hedgewars, a free turn based strategy game +# Copyright (c) 2011 Richard Deurwaarder +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; version 2 of the License +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA +################################################################################### + + + + +################################################################################### +# Uncomment (remove the leading '#') and change the paths accordingly to your own +# build environment, please do specify an absolute path (/home/richard/SoftDev +# rather than ~/SoftDev). +# You only need to change the three lines below, after that you can run 'cmake .' +# from the hedgewars root directory +# +# optionally you can specify SDL_DIR this will move the required SDL libraries to +# the correct place +################################################################################## + +set(ANDROID_NDK /home/richard/SoftDev/android/android-ndk-r5b) +set(ANDROID_SDK /home/richard/SoftDev/android/android-sdk-linux_86) +set(FPC_DIR /home/richard/SoftDev/fpc-2.4.4) +set(SDL_DIR /home/richard/Downloads/android-project) +set(LUA_DIR /home/richard/Downloads/lua-5.1.4) + +if(ANDROID_NDK AND ANDROID_SDK AND FPC_DIR) + + set(ANDROID_SDK_API_LVL 8) + set(ANDROID_NDK_API_LVL 5) + + MESSAGE("Creating android scripts and configuration files") + + configure_file(Templates/complete_build.sh .) + configure_file(Templates/default.properties SDL-android-project/) + configure_file(Templates/local.properties SDL-android-project/) + configure_file(Templates/Makefile.android .) + configure_file(Templates/pushToDevice.sh .) + + if(SDL_DIR) + + MESSAGE("Moving Android port of SDL to the proper directories") + + set(DirsToCopy + SDL + SDL_image + SDL_mixer + SDL_ttf + jpeg + png + mikmod + tremor + freetype + ) + foreach(DIR ${DirsToCopy}) + exec_program( + ${CMAKE_COMMAND} + ARGS -E copy_directory + ${SDL_DIR}/jni/${DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/SDL-android-project/jni/${DIR} + ) + MESSAGE("Moved ${DIR}") + endforeach(DIR) + exec_program(${HGCOMMAND} + ARGS revert ${CMAKE_CURRENT_SOURCE_DIR}/SDL-android-project/jni/SDL/src/core/android/SDL_android.cpp + ) + exec_program(${HGCOMMAND} + ARGS revert ${CMAKE_CURRENT_SOURCE_DIR}/SDL-android-project/jni/SDL/src/main/android/SDL_android_main.cpp + ) + exec_program(${HGCOMMAND} + ARGS revert ${CMAKE_CURRENT_SOURCE_DIR}/SDL-android-project/jni/SDL/src/video/android/SDL_androidtouch.c + ) + + exec_program(${HGCOMMAND} + ARGS revert ${CMAKE_CURRENT_SOURCE_DIR}/SDL-android-project/jni/SDL/src/video/android/SDL_androidtouch.h + ) + + + else(SDL_DIR) + MESSAGE("Android port of SDL not moved..") + endif(SDL_DIR) + + + if(LUA_DIR) + MESSAGE("Moving Lua dir..") + + exec_program( + ${CMAKE_COMMAND} + ARGS -E copy_directory + ${LUA_DIR}/src + ${CMAKE_CURRENT_SOURCE_DIR}/SDL-android-project/jni/lua-5.1.4 + ) + MESSAGE("Lua has been moved.") + + exec_program(${HGCOMMAND} + ARGS revert ${CMAKE_CURRENT_SOURCE_DIR}/SDL-android-project/jni/lua-5.1.4/Android.mk + ) + exec_program(${HGCOMMAND} + ARGS revert ${CMAKE_CURRENT_SOURCE_DIR}/SDL-android-project/jni/lua-5.1.4/llex.c + ) + else(LUA_DIR) + MESSAGE("Lua hasn't been moved..") + endif(LUA_DIR) + +else(ANDROID_AND AND ANDROID_SDK AND FPC_DIR) + MESSAGE("Android port files not created, edit top of ${CMAKE_CURRENT_SOURCE_DIR}/CMakeList.txt to create android specific files") +endif(ANDROID_NDK AND ANDROID_SDK AND FPC_DIR) + + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/AndroidManifest.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/AndroidManifest.xml Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/build.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/build.properties Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,17 @@ +# This file is used to override default values used by the Ant build system. +# +# This file must be checked in Version Control Systems, as it is +# integral to the build system of your project. + +# This file is only used by the Ant script. + +# You can use this to override default values such as +# 'source.dir' for the location of your java source folder and +# 'out.dir' for the location of your output folder. + +# You can also use it define how the release builds are signed by declaring +# the following properties: +# 'key.store' for the location of your keystore and +# 'key.alias' for the name of the key to use. +# The password will be asked during the build when you use the 'release' target. + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/build.xml Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/Android.mk --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/Android.mk Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,2 @@ +include $(call all-subdir-makefiles) + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/SDL/src/core/android/SDL_android.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/SDL/src/core/android/SDL_android.cpp Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,263 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2011 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" +#include "SDL_stdinc.h" + +#include "SDL_android.h" + +extern "C" { +#include "../../events/SDL_events_c.h" +#include "../../video/android/SDL_androidkeyboard.h" +#include "../../video/android/SDL_androidtouch.h" +#include "../../video/android/SDL_androidvideo.h" + +/* Impelemented in audio/android/SDL_androidaudio.c */ +extern void Android_RunAudioThread(); +} // C + +/******************************************************************************* + This file links the Java side of Android with libsdl +*******************************************************************************/ +#include +#include + + +/******************************************************************************* + Globals +*******************************************************************************/ +static JNIEnv* mEnv = NULL; +static JNIEnv* mAudioEnv = NULL; + +// Main activity +static jclass mActivityClass; + +// method signatures +static jmethodID midCreateGLContext; +static jmethodID midFlipBuffers; +static jmethodID midAudioInit; +static jmethodID midAudioWriteShortBuffer; +static jmethodID midAudioWriteByteBuffer; +static jmethodID midAudioQuit; + +// Accelerometer data storage +static float fLastAccelerometer[3]; + + +/******************************************************************************* + Functions called by JNI +*******************************************************************************/ + +// Library init +extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved) +{ + return JNI_VERSION_1_4; +} + +// Called before SDL_main() to initialize JNI bindings +extern "C" void SDL_Android_Init(JNIEnv* env, jclass cls) +{ + __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init()"); + + mEnv = env; + mActivityClass = cls; + + midCreateGLContext = mEnv->GetStaticMethodID(mActivityClass, + "createGLContext","(II)Z"); + midFlipBuffers = mEnv->GetStaticMethodID(mActivityClass, + "flipBuffers","()V"); + midAudioInit = mEnv->GetStaticMethodID(mActivityClass, + "audioInit", "(IZZI)Ljava/lang/Object;"); + midAudioWriteShortBuffer = mEnv->GetStaticMethodID(mActivityClass, + "audioWriteShortBuffer", "([S)V"); + midAudioWriteByteBuffer = mEnv->GetStaticMethodID(mActivityClass, + "audioWriteByteBuffer", "([B)V"); + midAudioQuit = mEnv->GetStaticMethodID(mActivityClass, + "audioQuit", "()V"); + + if(!midCreateGLContext || !midFlipBuffers || !midAudioInit || + !midAudioWriteShortBuffer || !midAudioWriteByteBuffer || !midAudioQuit) { + __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL: Couldn't locate Java callbacks, check that they're named and typed correctly"); + } +} + +// Resize +extern "C" void Java_org_hedgewars_mobile_SDLActivity_onNativeResize( + JNIEnv* env, jclass jcls, + jint width, jint height, jint format) +{ + Android_SetScreenResolution(width, height, format); +} + +// Keydown +extern "C" void Java_org_hedgewars_mobile_SDLActivity_onNativeKeyDown( + JNIEnv* env, jclass jcls, jint keycode) +{ + Android_OnKeyDown(keycode); +} + +// Keyup +extern "C" void Java_org_hedgewars_mobile_SDLActivity_onNativeKeyUp( + JNIEnv* env, jclass jcls, jint keycode) +{ + Android_OnKeyUp(keycode); +} + +// Touch +extern "C" void Java_org_hedgewars_mobile_SDLActivity_onNativeTouch( + JNIEnv* env, jclass jcls, + jint action, jint pointerId, jfloat x, jfloat y, jfloat p) +{ + Android_OnTouch(action, pointerId, x, y, p); +} + +// Accelerometer +extern "C" void Java_org_hedgewars_mobile_SDLActivity_onNativeAccel( + JNIEnv* env, jclass jcls, + jfloat x, jfloat y, jfloat z) +{ + fLastAccelerometer[0] = x; + fLastAccelerometer[1] = y; + fLastAccelerometer[2] = z; +} + +// Quit +extern "C" void Java_org_hedgewars_mobile_SDLActivity_nativeQuit( + JNIEnv* env, jclass cls) +{ + // Inject a SDL_QUIT event + SDL_SendQuit(); +} + +extern "C" void Java_org_hedgewars_mobile_SDLActivity_nativeRunAudioThread( + JNIEnv* env, jclass cls) +{ + /* This is the audio thread, with a different environment */ + mAudioEnv = env; + + Android_RunAudioThread(); +} + + +/******************************************************************************* + Functions called by SDL into Java +*******************************************************************************/ +extern "C" SDL_bool Android_JNI_CreateContext(int majorVersion, int minorVersion) +{ + if (mEnv->CallStaticBooleanMethod(mActivityClass, midCreateGLContext, majorVersion, minorVersion)) { + return SDL_TRUE; + } else { + return SDL_FALSE; + } +} + +extern "C" void Android_JNI_SwapWindow() +{ + mEnv->CallStaticVoidMethod(mActivityClass, midFlipBuffers); +} + +extern "C" void Android_JNI_SetActivityTitle(const char *title) +{ + jmethodID mid; + + mid = mEnv->GetStaticMethodID(mActivityClass,"setActivityTitle","(Ljava/lang/String;)V"); + if (mid) { + mEnv->CallStaticVoidMethod(mActivityClass, mid, mEnv->NewStringUTF(title)); + } +} + +extern "C" void Android_JNI_GetAccelerometerValues(float values[3]) +{ + int i; + for (i = 0; i < 3; ++i) { + values[i] = fLastAccelerometer[i]; + } +} + +// +// Audio support +// +static jboolean audioBuffer16Bit = JNI_FALSE; +static jboolean audioBufferStereo = JNI_FALSE; +static jobject audioBuffer = NULL; +static void* audioBufferPinned = NULL; + +extern "C" int Android_JNI_OpenAudioDevice(int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames) +{ + int audioBufferFrames; + + __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device"); + audioBuffer16Bit = is16Bit; + audioBufferStereo = channelCount > 1; + + audioBuffer = mEnv->CallStaticObjectMethod(mActivityClass, midAudioInit, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames); + + if (audioBuffer == NULL) { + __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: didn't get back a good audio buffer!"); + return 0; + } + audioBuffer = mEnv->NewGlobalRef(audioBuffer); + + jboolean isCopy = JNI_FALSE; + if (audioBuffer16Bit) { + audioBufferPinned = mEnv->GetShortArrayElements((jshortArray)audioBuffer, &isCopy); + audioBufferFrames = mEnv->GetArrayLength((jshortArray)audioBuffer); + } else { + audioBufferPinned = mEnv->GetByteArrayElements((jbyteArray)audioBuffer, &isCopy); + audioBufferFrames = mEnv->GetArrayLength((jbyteArray)audioBuffer); + } + if (audioBufferStereo) { + audioBufferFrames /= 2; + } + + return audioBufferFrames; +} + +extern "C" void * Android_JNI_GetAudioBuffer() +{ + return audioBufferPinned; +} + +extern "C" void Android_JNI_WriteAudioBuffer() +{ + if (audioBuffer16Bit) { + mAudioEnv->ReleaseShortArrayElements((jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT); + mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer); + } else { + mAudioEnv->ReleaseByteArrayElements((jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT); + mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer); + } + + /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */ +} + +extern "C" void Android_JNI_CloseAudioDevice() +{ + mEnv->CallStaticVoidMethod(mActivityClass, midAudioQuit); + + if (audioBuffer) { + mEnv->DeleteGlobalRef(audioBuffer); + audioBuffer = NULL; + audioBufferPinned = NULL; + } +} + +/* vi: set ts=4 sw=4 expandtab: */ diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/SDL/src/main/android/SDL_android_main.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/SDL/src/main/android/SDL_android_main.cpp Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,49 @@ + +/* Include the SDL main definition header */ +#include "SDL_main.h" + +/******************************************************************************* + Functions called by JNI +*******************************************************************************/ +#include + +// Called before SDL_main() to initialize JNI bindings in SDL library +extern "C" void SDL_Android_Init(JNIEnv* env, jclass cls); + +// Library init +extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved) +{ + return JNI_VERSION_1_4; +} + +// Start up the SDL app +extern "C" void Java_org_hedgewars_mobile_SDLActivity_nativeInit(JNIEnv* env, jclass cls, jobjectArray strArray) +{ + /* This interface could expand with ABI negotiation, calbacks, etc. */ + SDL_Android_Init(env, cls); + + //Get the String array from java + int argc = env->GetArrayLength(strArray); + char *argv[argc]; + jstring jstringArgv[argc]; + for(int i = 0; i < argc; i++){ + jstringArgv[i] = (jstring)env->GetObjectArrayElement(strArray, i); //get the element + argv[i] = (char*)malloc(sizeof(char) * env->GetStringLength(jstringArgv[i])); + strcpy(argv[i], env->GetStringUTFChars(jstringArgv[i], JNI_FALSE)); //copy it to a mutable location + //Don't release memory the JAVA GC will take care of it + //env->ReleaseStringChars(jstringArgv[i], (jchar*)argv[i]); + } + + /* Run the application code! */ + int status; + status = SDL_main(argc, argv); + + //Clean up argv + for(int i = 0; i < argc; i++){ + } + + /* We exit here for consistency with other platforms. */ + exit(status); +} + +/* vi: set ts=4 sw=4 expandtab: */ diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/SDL/src/video/android/SDL_androidtouch.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/SDL/src/video/android/SDL_androidtouch.c Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,83 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2011 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +#include + +#include "SDL_events.h" +#include "../../events/SDL_touch_c.h" + +#include "SDL_androidtouch.h" +#include "stdlib.h" + +#define ACTION_DOWN 0 +#define ACTION_UP 1 +#define ACTION_MOVE 2 +#define ACTION_CANCEL 3 +#define ACTION_OUTSIDE 4 +#define ACTION_POINTER_DOWN 5 +#define ACTION_POINTER_UP 6 + + +void Android_OnTouch(int action, SDL_FingerID pointerId, float x, float y, float p) +{ + if (!Android_Window) { + return; + } + + //The first event will provide the x, y and pressure max values, + if(!SDL_GetTouch(1)){ + SDL_Touch touch; + touch.id = 1; + touch.x_min = 0; + touch.x_max = x; + touch.native_xres = touch.x_max - touch.x_min; + touch.y_min = 0; + touch.y_max = y; + touch.native_yres = touch.y_max - touch.y_min; + touch.pressure_min = 0; + touch.pressure_max = p; + touch.native_pressureres = touch.pressure_max - touch.pressure_min; + + if(SDL_AddTouch(&touch, "") < 0) return; + } + + switch(action){ + case ACTION_DOWN: + case ACTION_POINTER_DOWN: + SDL_SetTouchFocus(pointerId, Android_Window); + SDL_SendFingerDown(1, pointerId, SDL_TRUE, x, y, p); + break; + case ACTION_CANCEL: + case ACTION_POINTER_UP: + case ACTION_UP: + SDL_SendFingerDown(1, pointerId, SDL_FALSE, x, y, p); + break; + case ACTION_MOVE: + SDL_SendTouchMotion(1, pointerId, 0, x, y, p); + break; + case ACTION_OUTSIDE: + break; + } +} + +/* vi: set ts=4 sw=4 expandtab: */ diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/SDL/src/video/android/SDL_androidtouch.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/SDL/src/video/android/SDL_androidtouch.h Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,28 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2011 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ +#include "SDL_config.h" + +#include "SDL_androidvideo.h" + +extern void Android_OnTouch(int action, SDL_FingerID pointerId, float x, float y, float p); + +/* vi: set ts=4 sw=4 expandtab: */ diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/lua-5.1.4/Android.mk --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/lua-5.1.4/Android.mk Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,10 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := lua5.1 +LOCAL_SRC_FILES := lapi.c lauxlib.c lbaselib.c lcode.c ldblib.c ldebug.c ldo.c ldump.c lfunc.c lgc.c linit.c liolib.c llex.c lmathlib.c lmem.c loadlib.c lobject.c lopcodes.c loslib.c lparser.c lstate.c lstring.c lstrlib.c ltable.c ltablib.c ltm.c lundump.c lvm.c lzio.c + +include $(BUILD_SHARED_LIBRARY) + + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/lua-5.1.4/llex.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/lua-5.1.4/llex.c Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,462 @@ +/* +** $Id: llex.c,v 2.20.1.1 2007/12/27 13:02:25 roberto Exp $ +** Lexical Analyzer +** See Copyright Notice in lua.h +*/ + + +#include +#include +#include + +#define llex_c +#define LUA_CORE + +#include "lua.h" + +#include "ldo.h" +#include "llex.h" +#include "lobject.h" +#include "lparser.h" +#include "lstate.h" +#include "lstring.h" +#include "ltable.h" +#include "lzio.h" + + + +#define next(ls) (ls->current = zgetc(ls->z)) + + + + +#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') + + +/* ORDER RESERVED */ +const char *const luaX_tokens [] = { + "and", "break", "do", "else", "elseif", + "end", "false", "for", "function", "if", + "in", "local", "nil", "not", "or", "repeat", + "return", "then", "true", "until", "while", + "..", "...", "==", ">=", "<=", "~=", + "", "", "", "", + NULL +}; + + +#define save_and_next(ls) (save(ls, ls->current), next(ls)) + + +static void save (LexState *ls, int c) { + Mbuffer *b = ls->buff; + if (b->n + 1 > b->buffsize) { + size_t newsize; + if (b->buffsize >= MAX_SIZET/2) + luaX_lexerror(ls, "lexical element too long", 0); + newsize = b->buffsize * 2; + luaZ_resizebuffer(ls->L, b, newsize); + } + b->buffer[b->n++] = cast(char, c); +} + + +void luaX_init (lua_State *L) { + int i; + for (i=0; itsv.reserved = cast_byte(i+1); /* reserved word */ + } +} + + +#define MAXSRC 80 + + +const char *luaX_token2str (LexState *ls, int token) { + if (token < FIRST_RESERVED) { + lua_assert(token == cast(unsigned char, token)); + return (iscntrl(token)) ? luaO_pushfstring(ls->L, "char(%d)", token) : + luaO_pushfstring(ls->L, "%c", token); + } + else + return luaX_tokens[token-FIRST_RESERVED]; +} + + +static const char *txtToken (LexState *ls, int token) { + switch (token) { + case TK_NAME: + case TK_STRING: + case TK_NUMBER: + save(ls, '\0'); + return luaZ_buffer(ls->buff); + default: + return luaX_token2str(ls, token); + } +} + + +void luaX_lexerror (LexState *ls, const char *msg, int token) { + char buff[MAXSRC]; + luaO_chunkid(buff, getstr(ls->source), MAXSRC); + msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg); + if (token) + luaO_pushfstring(ls->L, "%s near " LUA_QS, msg, txtToken(ls, token)); + luaD_throw(ls->L, LUA_ERRSYNTAX); +} + + +void luaX_syntaxerror (LexState *ls, const char *msg) { + luaX_lexerror(ls, msg, ls->t.token); +} + + +TString *luaX_newstring (LexState *ls, const char *str, size_t l) { + lua_State *L = ls->L; + TString *ts = luaS_newlstr(L, str, l); + TValue *o = luaH_setstr(L, ls->fs->h, ts); /* entry for `str' */ + if (ttisnil(o)) + setbvalue(o, 1); /* make sure `str' will not be collected */ + return ts; +} + + +static void inclinenumber (LexState *ls) { + int old = ls->current; + lua_assert(currIsNewline(ls)); + next(ls); /* skip `\n' or `\r' */ + if (currIsNewline(ls) && ls->current != old) + next(ls); /* skip `\n\r' or `\r\n' */ + if (++ls->linenumber >= MAX_INT) + luaX_syntaxerror(ls, "chunk has too many lines"); +} + + +void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source) { + ls->decpoint = '.'; + ls->L = L; + ls->lookahead.token = TK_EOS; /* no look-ahead token */ + ls->z = z; + ls->fs = NULL; + ls->linenumber = 1; + ls->lastline = 1; + ls->source = source; + luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ + next(ls); /* read first char */ +} + + + +/* +** ======================================================= +** LEXICAL ANALYZER +** ======================================================= +*/ + + + +static int check_next (LexState *ls, const char *set) { + if (!strchr(set, ls->current)) + return 0; + save_and_next(ls); + return 1; +} + + +static void buffreplace (LexState *ls, char from, char to) { + size_t n = luaZ_bufflen(ls->buff); + char *p = luaZ_buffer(ls->buff); + while (n--) + if (p[n] == from) p[n] = to; +} + + +static void trydecpoint (LexState *ls, SemInfo *seminfo) { + /* format error: try to update decimal point separator */ + //struct lconv *cv = localeconv(); + char old = ls->decpoint; + //ls->decpoint = (cv ? cv->decimal_point[0] : '.'); + ls->decpoint = '.'; + buffreplace(ls, old, ls->decpoint); /* try updated decimal separator */ + if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) { + /* format error with correct decimal point: no more options */ + buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */ + luaX_lexerror(ls, "malformed number", TK_NUMBER); + } +} + + +/* LUA_NUMBER */ +static void read_numeral (LexState *ls, SemInfo *seminfo) { + lua_assert(isdigit(ls->current)); + do { + save_and_next(ls); + } while (isdigit(ls->current) || ls->current == '.'); + if (check_next(ls, "Ee")) /* `E'? */ + check_next(ls, "+-"); /* optional exponent sign */ + while (isalnum(ls->current) || ls->current == '_') + save_and_next(ls); + save(ls, '\0'); + buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */ + if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) /* format error? */ + trydecpoint(ls, seminfo); /* try to update decimal point separator */ +} + + +static int skip_sep (LexState *ls) { + int count = 0; + int s = ls->current; + lua_assert(s == '[' || s == ']'); + save_and_next(ls); + while (ls->current == '=') { + save_and_next(ls); + count++; + } + return (ls->current == s) ? count : (-count) - 1; +} + + +static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { + int cont = 0; + (void)(cont); /* avoid warnings when `cont' is not used */ + save_and_next(ls); /* skip 2nd `[' */ + if (currIsNewline(ls)) /* string starts with a newline? */ + inclinenumber(ls); /* skip it */ + for (;;) { + switch (ls->current) { + case EOZ: + luaX_lexerror(ls, (seminfo) ? "unfinished long string" : + "unfinished long comment", TK_EOS); + break; /* to avoid warnings */ +#if defined(LUA_COMPAT_LSTR) + case '[': { + if (skip_sep(ls) == sep) { + save_and_next(ls); /* skip 2nd `[' */ + cont++; +#if LUA_COMPAT_LSTR == 1 + if (sep == 0) + luaX_lexerror(ls, "nesting of [[...]] is deprecated", '['); +#endif + } + break; + } +#endif + case ']': { + if (skip_sep(ls) == sep) { + save_and_next(ls); /* skip 2nd `]' */ +#if defined(LUA_COMPAT_LSTR) && LUA_COMPAT_LSTR == 2 + cont--; + if (sep == 0 && cont >= 0) break; +#endif + goto endloop; + } + break; + } + case '\n': + case '\r': { + save(ls, '\n'); + inclinenumber(ls); + if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */ + break; + } + default: { + if (seminfo) save_and_next(ls); + else next(ls); + } + } + } endloop: + if (seminfo) + seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep), + luaZ_bufflen(ls->buff) - 2*(2 + sep)); +} + + +static void read_string (LexState *ls, int del, SemInfo *seminfo) { + save_and_next(ls); + while (ls->current != del) { + switch (ls->current) { + case EOZ: + luaX_lexerror(ls, "unfinished string", TK_EOS); + continue; /* to avoid warnings */ + case '\n': + case '\r': + luaX_lexerror(ls, "unfinished string", TK_STRING); + continue; /* to avoid warnings */ + case '\\': { + int c; + next(ls); /* do not save the `\' */ + switch (ls->current) { + case 'a': c = '\a'; break; + case 'b': c = '\b'; break; + case 'f': c = '\f'; break; + case 'n': c = '\n'; break; + case 'r': c = '\r'; break; + case 't': c = '\t'; break; + case 'v': c = '\v'; break; + case '\n': /* go through */ + case '\r': save(ls, '\n'); inclinenumber(ls); continue; + case EOZ: continue; /* will raise an error next loop */ + default: { + if (!isdigit(ls->current)) + save_and_next(ls); /* handles \\, \", \', and \? */ + else { /* \xxx */ + int i = 0; + c = 0; + do { + c = 10*c + (ls->current-'0'); + next(ls); + } while (++i<3 && isdigit(ls->current)); + if (c > UCHAR_MAX) + luaX_lexerror(ls, "escape sequence too large", TK_STRING); + save(ls, c); + } + continue; + } + } + save(ls, c); + next(ls); + continue; + } + default: + save_and_next(ls); + } + } + save_and_next(ls); /* skip delimiter */ + seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1, + luaZ_bufflen(ls->buff) - 2); +} + + +static int llex (LexState *ls, SemInfo *seminfo) { + luaZ_resetbuffer(ls->buff); + for (;;) { + switch (ls->current) { + case '\n': + case '\r': { + inclinenumber(ls); + continue; + } + case '-': { + next(ls); + if (ls->current != '-') return '-'; + /* else is a comment */ + next(ls); + if (ls->current == '[') { + int sep = skip_sep(ls); + luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */ + if (sep >= 0) { + read_long_string(ls, NULL, sep); /* long comment */ + luaZ_resetbuffer(ls->buff); + continue; + } + } + /* else short comment */ + while (!currIsNewline(ls) && ls->current != EOZ) + next(ls); + continue; + } + case '[': { + int sep = skip_sep(ls); + if (sep >= 0) { + read_long_string(ls, seminfo, sep); + return TK_STRING; + } + else if (sep == -1) return '['; + else luaX_lexerror(ls, "invalid long string delimiter", TK_STRING); + } + case '=': { + next(ls); + if (ls->current != '=') return '='; + else { next(ls); return TK_EQ; } + } + case '<': { + next(ls); + if (ls->current != '=') return '<'; + else { next(ls); return TK_LE; } + } + case '>': { + next(ls); + if (ls->current != '=') return '>'; + else { next(ls); return TK_GE; } + } + case '~': { + next(ls); + if (ls->current != '=') return '~'; + else { next(ls); return TK_NE; } + } + case '"': + case '\'': { + read_string(ls, ls->current, seminfo); + return TK_STRING; + } + case '.': { + save_and_next(ls); + if (check_next(ls, ".")) { + if (check_next(ls, ".")) + return TK_DOTS; /* ... */ + else return TK_CONCAT; /* .. */ + } + else if (!isdigit(ls->current)) return '.'; + else { + read_numeral(ls, seminfo); + return TK_NUMBER; + } + } + case EOZ: { + return TK_EOS; + } + default: { + if (isspace(ls->current)) { + lua_assert(!currIsNewline(ls)); + next(ls); + continue; + } + else if (isdigit(ls->current)) { + read_numeral(ls, seminfo); + return TK_NUMBER; + } + else if (isalpha(ls->current) || ls->current == '_') { + /* identifier or reserved word */ + TString *ts; + do { + save_and_next(ls); + } while (isalnum(ls->current) || ls->current == '_'); + ts = luaX_newstring(ls, luaZ_buffer(ls->buff), + luaZ_bufflen(ls->buff)); + if (ts->tsv.reserved > 0) /* reserved word? */ + return ts->tsv.reserved - 1 + FIRST_RESERVED; + else { + seminfo->ts = ts; + return TK_NAME; + } + } + else { + int c = ls->current; + next(ls); + return c; /* single-char tokens (+ - / ...) */ + } + } + } + } +} + + +void luaX_next (LexState *ls) { + ls->lastline = ls->linenumber; + if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */ + ls->t = ls->lookahead; /* use this one */ + ls->lookahead.token = TK_EOS; /* and discharge it */ + } + else + ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */ +} + + +void luaX_lookahead (LexState *ls) { + lua_assert(ls->lookahead.token == TK_EOS); + ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); +} + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/sdl_net/Android.mk --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/sdl_net/Android.mk Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,19 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := SDL_net + +LOCAL_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/../SDL/include $(LOCAL_PATH)/include +LOCAL_CFLAGS := -O3 + +LOCAL_CPP_EXTENSION := .cpp + +LOCAL_SRC_FILES := $(notdir $(wildcard $(LOCAL_PATH)/*.c)) + +LOCAL_SHARED_LIBRARIES := SDL +LOCAL_STATIC_LIBRARIES := +LOCAL_LDLIBS := + +include $(BUILD_SHARED_LIBRARY) + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/sdl_net/CHANGES --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/sdl_net/CHANGES Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,83 @@ +1.2.7: +Joakim L. Gilje - Sat Jul 14 22:54:37 PDT 2007 + * Set server TCP sockets to blocking mode on Mac OS X, Solaris, etc. + +1.2.6: +Sam Lantinga - Sun Apr 30 01:48:40 PDT 2006 + * Added gcc-fat.sh for generating Universal binaries on Mac OS X + * Updated libtool support to version 1.5.22 +Sam Lantinga - Wed Nov 19 00:23:44 PST 2003 + * Updated libtool support for new mingw32 DLL build process +Shard - Thu, 05 Jun 2003 09:30:20 -0500 + * Fixed compiling on BeOS, which may not have SO_BROADCAST +Kyle Davenport - Sat, 19 Apr 2003 17:13:31 -0500 + * Added .la files to the development RPM, fixing RPM build on RedHat 8 + +1.2.5: +Luc-Olivier de Charrière - Sun, 05 Jan 2003 22:04:29 +0100 + * Added support for sending UDP broadcast packets +Sam Lantinga - Sun Oct 20 20:54:41 PDT 2002 + * Added shared library support for MacOS X +Sam Lantinga - Sat Aug 24 18:16:08 PDT 2002 + * It is now safe to nest calls to SDLNet_Init() / SDLNet_Quit() +Gaëtan de Menten - Sat Aug 24 18:08:39 PDT 2002 + * Fixed UDP virtual address bind bug + +1.2.4: +Sam Lantinga - Sat Apr 13 07:49:47 PDT 2002 + * Updated autogen.sh for new versions of automake + * Specify the SDL API calling convention (C by default) +Stephane Magnenat - Wed Feb 13 15:28:04 PST 2002 + * Sockets are created with the SO_REUSEADDR flag by default +Juergen Wind - Wed Feb 13 09:21:55 PST 2002 + * Fixed data alignment problems on IRIX + +1.2.3: +Sam Lantinga - Fri Oct 26 07:15:28 PDT 2001 + * Fixed byte order read/write macros on sparc +Jonathan Atkins - Sun Sep 23 10:44:27 PDT 2001 + * Fixed non-blocking socket flags on Windows + +1.2.2: +Sam Lantinga - Sun Jul 22 16:41:44 PDT 2001 + * Added Project Builder projects for building MacOS X framework +Masahiro Minami - Sun, 27 May 2001 02:10:35 +0900 + * Added working MacOS Open Transport support + +1.2.1: +Sam Lantinga - Tue Apr 17 11:42:13 PDT 2001 + * Cleaned up swap function definitions in SDL_net.h + * Added the swap functions back in for binary compatibility +Paul Jenner - Sat, 14 Apr 2001 09:20:38 -0700 (PDT) + * Added support for building RPM directly from tar archive + +1.2.0: +Sam Lantinga - Wed Apr 4 12:42:20 PDT 2001 + * Synchronized release version with SDL 1.2.0 + +1.1.2: +Sam Lantinga - Sat Feb 10 16:33:59 PST 2001 + * SDL_net works with the sockets API out of the box on MacOS X. +Paul S Jenner - Sun, 4 Feb 2001 03:58:44 -0800 (PST) + * Added an RPM spec file +Patrick Levin - Mon, 8 Jan 2001 23:20:11 +0100 + * Fixed non-blocking socket modes on Win32 +John Lawrence - Mon, 13 Nov 2000 10:39:48 -0800 + * Fixed compile problem with MSVC++ (type casting) + +1.1.1: +Sam Lantinga - Sat Jul 1 15:20:51 PDT 2000 + * Modified chat example to work with GUIlib 1.1.0 +Roy Wood - Fri Jun 30 10:41:05 PDT 2000 + * A few MacOS fixes (not yet complete) + +1.1.0: +Andreas Umbach - Sat May 27 14:44:06 PDT 2000 + * Suggested non-blocking server sockets + * Suggested setting TCP_NODELAY by default +Roy Wood - Sat May 27 14:41:42 PDT 2000 + * Ported to MacOS (not yet complete) + +1.0.2: +Miguel Angel Blanch - Sat, 22 Apr 2000 23:06:05 + * Implemented SDLNet_ResolveIP() diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/sdl_net/COPYING --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/sdl_net/COPYING Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,458 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/sdl_net/README --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/sdl_net/README Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,27 @@ + +SDL_net 1.2 + +The latest version of this library is available from: +http://www.libsdl.org/projects/SDL_net/ + +This is an example portable network library for use with SDL. +It is available under the GNU Library General Public License. +The API can be found in the file SDL_net.h +This library supports UNIX, Windows, MacOS Classic, MacOS X, +BeOS and QNX. + +The demo program is a chat client and server. +The chat client requires the sample GUI library available at: +http://www.libsdl.org/projects/GUIlib/ +The chat client connects to the server via TCP, registering itself. +The server sends back a list of connected clients, and keeps the +client updated with the status of other clients. +Every line of text from a client is sent via UDP to every other client. + +Note that this isn't necessarily how you would want to write a chat +program, but it demonstrates how to use the basic features of the +network library. + +Enjoy! + -Sam Lantinga and Roy Wood + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/sdl_net/SDLnet.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/sdl_net/SDLnet.c Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,430 @@ +/* + SDL_net: An example cross-platform network library for use with SDL + Copyright (C) 1997-2004 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/* $Id: SDLnet.c 2207 2006-04-20 16:48:25Z slouken $ */ + +#include + +#include "SDL_endian.h" + +#include "SDLnetsys.h" +#include "SDL_net.h" + + +const SDL_version *SDLNet_Linked_Version(void) +{ + static SDL_version linked_version; + SDL_NET_VERSION(&linked_version); + return(&linked_version); +} + +/* Since the UNIX/Win32/BeOS code is so different from MacOS, + we'll just have two completely different sections here. +*/ +static int SDLNet_started = 0; + +#ifdef MACOS_OPENTRANSPORT + +#include + +typedef struct +{ + Uint8 stat; + InetSvcRef dns; +}DNSStatus, *DNSStatusRef; + +enum +{ + dnsNotReady = 0, + dnsReady = 1, + dnsResolved = 2, + dnsError = 255 +}; + +//static InetSvcRef dns = 0; +static DNSStatus dnsStatus; +Uint32 OTlocalhost = 0; + +/* We need a notifier for opening DNS.*/ +/* ( 010311 masahiro minami) */ +static pascal void OpenDNSNotifier( + void* context, OTEventCode code, OTResult result, void* cookie ) +{ + switch( code ) + { + case T_OPENCOMPLETE: + // DNS is ready now. + if( result == kOTNoError ) + { + dnsStatus.dns = (InetSvcRef)cookie; + dnsStatus.stat = dnsReady; + } + else + { + SDLNet_SetError("T_DNRSTRINGTOADDRCOMPLETE event returned an error"); + dnsStatus.dns = NULL; + dnsStatus.stat = dnsError; + } + break; + case T_DNRSTRINGTOADDRCOMPLETE: + // DNR resolved the name to address + // WORK IN PROGRESS (TODO ) + dnsStatus.stat = dnsResolved; + break; + default: + if( result != kOTNoError ) + dnsStatus.stat = dnsError; + } + // Is there anything else to be done here ??? + // ( 010311 masahiro minami ) + // (TODO) +} + +/* Local functions for initializing and cleaning up the DNS resolver */ +static int OpenDNS(void) +{ + int retval; + OSStatus status; + + retval = 0; + status = OTAsyncOpenInternetServices( + kDefaultInternetServicesPath, 0, OpenDNSNotifier, NULL); + if ( status == noErr ) { + InetInterfaceInfo info; + + dnsStatus.stat = dnsNotReady; + + while( dnsStatus.stat != dnsError && dnsStatus.dns == NULL) + { + // what's to be done ? Yield ? WaitNextEvent ? or what ? + // ( 010311 masahiro minami ) + //YieldToAnyThread(); + } + /* Get the address of the local system - + What should it be if ethernet is off? + */ + OTInetGetInterfaceInfo(&info, kDefaultInetInterface); + OTlocalhost = info.fAddress; + } else { + SDLNet_SetError("Unable to open DNS handle"); + retval = status; + } + + return(retval); +} + +static void CloseDNS(void) +{ + if ( dnsStatus.dns ) { + OTCloseProvider(dnsStatus.dns); + dnsStatus.dns = 0; + dnsStatus.stat = dnsNotReady; + } + + OTlocalhost = 0; +} + +/* Initialize/Cleanup the network API */ +int SDLNet_Init(void) +{ + OSStatus status; + int retval; + + dnsStatus.stat = dnsNotReady; + dnsStatus.dns = 0; + + + retval = 0; + if ( ! SDLNet_started ) { + status = InitOpenTransport(); + if ( status == noErr ) { + retval = OpenDNS(); + if ( retval < 0 ) { + SDLNet_Quit(); + } + } else { + SDLNet_SetError("Unable to initialize Open Transport"); + retval = status; + } + } + if ( retval == 0 ) { + ++SDLNet_started; + } + return(retval); +} + +void SDLNet_Quit(void) +{ + if ( SDLNet_started == 0 ) { + return; + } + if ( --SDLNet_started == 0 ) { + CloseDNS(); + CloseOpenTransport(); + } +} + +/* Resolve a host name and port to an IP address in network form */ +int SDLNet_ResolveHost(IPaddress *address, const char *host, Uint16 port) +{ + int retval = 0; + + /* Perform the actual host resolution */ + if ( host == NULL ) { + address->host = INADDR_ANY; + } else { +/* int a[4]; + + address->host = INADDR_NONE; + + if ( sscanf(host, "%d.%d.%d.%d", a, a+1, a+2, a+3) == 4 ) { + if ( !(a[0] & 0xFFFFFF00) && !(a[1] & 0xFFFFFF00) && + !(a[2] & 0xFFFFFF00) && !(a[3] & 0xFFFFFF00) ) { + address->host = ((a[0] << 24) | + (a[1] << 16) | + (a[2] << 8) | a[3]); + if ( address->host == 0x7F000001 ) { + address->host = OTlocalhost; + } + } + } + + if ( address->host == INADDR_NONE ) {*/ + InetHostInfo hinfo; + + /* Check for special case - localhost */ + if ( strcmp(host, "localhost") == 0 ) + return(SDLNet_ResolveHost(address, "127.0.0.1", port)); + + /* Have OpenTransport resolve the hostname for us */ + retval = OTInetStringToAddress(dnsStatus.dns, (char *)host, &hinfo); + if (retval == noErr) { + while( dnsStatus.stat != dnsResolved ) + {WaitNextEvent(everyEvent, 0, 1, NULL );} + address->host = hinfo.addrs[0]; + } + //} + } + + address->port = SDL_SwapBE16(port); + + /* Return the status */ + return(retval); +} + +/* Resolve an ip address to a host name in canonical form. + If the ip couldn't be resolved, this function returns NULL, + otherwise a pointer to a static buffer containing the hostname + is returned. Note that this function is not thread-safe. +*/ +/* MacOS implementation by Roy Wood + */ +const char *SDLNet_ResolveIP(IPaddress *ip) +{ + if (ip != nil) + { + InetHost theIP; + static InetDomainName theInetDomainName; + OSStatus theOSStatus; + + + /* Default result will be null string */ + + theInetDomainName[0] = '\0'; + + + /* Do a reverse DNS lookup */ + + theIP = ip->host; + + theOSStatus = OTInetAddressToName(dnsStatus.dns,theIP,theInetDomainName); + + /* If successful, return the result */ + + if (theOSStatus == kOTNoError) + { + while( dnsStatus.stat != dnsResolved ) + { /*should we yield or what ? */ } + return(theInetDomainName); + } + } + + SDLNet_SetError("Can't perform reverse DNS lookup"); + + return(NULL); +} + +#else /* !MACOS_OPENTRANSPORT */ + +#ifndef __USE_W32_SOCKETS +#include +#endif + +/* Initialize/Cleanup the network API */ +int SDLNet_Init(void) +{ + if ( !SDLNet_started ) { +#ifdef __USE_W32_SOCKETS + /* Start up the windows networking */ + WORD version_wanted = MAKEWORD(1,1); + WSADATA wsaData; + + if ( WSAStartup(version_wanted, &wsaData) != 0 ) { + SDLNet_SetError("Couldn't initialize Winsock 1.1\n"); + return(-1); + } +#else + /* SIGPIPE is generated when a remote socket is closed */ + void (*handler)(int); + handler = signal(SIGPIPE, SIG_IGN); + if ( handler != SIG_DFL ) { + signal(SIGPIPE, handler); + } +#endif + } + ++SDLNet_started; + return(0); +} +void SDLNet_Quit(void) +{ + if ( SDLNet_started == 0 ) { + return; + } + if ( --SDLNet_started == 0 ) { +#ifdef __USE_W32_SOCKETS + /* Clean up windows networking */ + if ( WSACleanup() == SOCKET_ERROR ) { + if ( WSAGetLastError() == WSAEINPROGRESS ) { + WSACancelBlockingCall(); + WSACleanup(); + } + } +#else + /* Restore the SIGPIPE handler */ + void (*handler)(int); + handler = signal(SIGPIPE, SIG_DFL); + if ( handler != SIG_IGN ) { + signal(SIGPIPE, handler); + } +#endif + } +} + +/* Resolve a host name and port to an IP address in network form */ +int SDLNet_ResolveHost(IPaddress *address, const char *host, Uint16 port) +{ + int retval = 0; + + /* Perform the actual host resolution */ + if ( host == NULL ) { + address->host = INADDR_ANY; + } else { + address->host = inet_addr(host); + if ( address->host == INADDR_NONE ) { + struct hostent *hp; + + hp = gethostbyname(host); + if ( hp ) { + memcpy(&address->host,hp->h_addr,hp->h_length); + } else { + retval = -1; + } + } + } + address->port = SDL_SwapBE16(port); + + /* Return the status */ + return(retval); +} + +/* Resolve an ip address to a host name in canonical form. + If the ip couldn't be resolved, this function returns NULL, + otherwise a pointer to a static buffer containing the hostname + is returned. Note that this function is not thread-safe. +*/ +/* Written by Miguel Angel Blanch. + * Main Programmer of Arianne RPG. + * http://come.to/arianne_rpg + */ +const char *SDLNet_ResolveIP(IPaddress *ip) +{ + struct hostent *hp; + + hp = gethostbyaddr((char *)&ip->host, 4, AF_INET); + if ( hp != NULL ) { + return hp->h_name; + } + return NULL; +} + +#endif /* MACOS_OPENTRANSPORT */ + +#if !SDL_DATA_ALIGNED /* function versions for binary compatibility */ + +/* Write a 16 bit value to network packet buffer */ +#undef SDLNet_Write16 +void SDLNet_Write16(Uint16 value, void *areap) +{ + (*(Uint16 *)(areap) = SDL_SwapBE16(value)); +} + +/* Write a 32 bit value to network packet buffer */ +#undef SDLNet_Write32 +void SDLNet_Write32(Uint32 value, void *areap) +{ + *(Uint32 *)(areap) = SDL_SwapBE32(value); +} + +/* Read a 16 bit value from network packet buffer */ +#undef SDLNet_Read16 +Uint16 SDLNet_Read16(void *areap) +{ + return (SDL_SwapBE16(*(Uint16 *)(areap))); +} + +/* Read a 32 bit value from network packet buffer */ +#undef SDLNet_Read32 +Uint32 SDLNet_Read32(void *areap) +{ + return (SDL_SwapBE32(*(Uint32 *)(areap))); +} + +#endif /* !SDL_DATA_ALIGNED */ + + +#ifdef USE_GUSI_SOCKETS + +/* Configure Socket Factories */ + +void GUSISetupFactories() +{ + GUSIwithInetSockets(); +} + +/* Configure File Devices */ + +void GUSISetupDevices() +{ + return; +} + +#endif /* USE_GUSI_SOCKETS */ diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/sdl_net/SDLnetTCP.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/sdl_net/SDLnetTCP.c Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,953 @@ +/* + SDL_net: An example cross-platform network library for use with SDL + Copyright (C) 1997-2004 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/* $Id: SDLnetTCP.c 3280 2007-07-15 05:55:42Z slouken $ */ + +#include "SDLnetsys.h" +#include "SDL_net.h" + +/* The network API for TCP sockets */ + +/* Since the UNIX/Win32/BeOS code is so different from MacOS, + we'll just have two completely different sections here. +*/ + +#ifdef MACOS_OPENTRANSPORT + +#include +#include +#include +#include +#include + +struct _TCPsocket { + int ready; + SOCKET channel; + + // These are taken from GUSI interface. + // I'm not sure if it's really necessary here yet + // ( masahiro minami ) + // ( 01/02/19 ) + OTEventCode curEvent; + OTEventCode newEvent; + OTEventCode event; + OTEventCode curCompletion; + OTEventCode newCompletion; + OTEventCode completion; + OSStatus error; + TEndpointInfo info; + Boolean readShutdown; + Boolean writeShutdown; + Boolean connected; + OTConfigurationRef config; // Master configuration. you can clone this. + TCPsocket nextListener; + // ( end of new members --- masahiro minami + + IPaddress remoteAddress; + IPaddress localAddress; + int sflag; + + // Maybe we don't need this---- it's from original SDL_net + // (masahiro minami) + // ( 01/02/20 ) + int rcvdPassConn; +}; + +// To be used in WaitNextEvent() here and there.... +// (010311 masahiro minami) +EventRecord macEvent; + +#if TARGET_API_MAC_CARBON +/* for Carbon */ +OTNotifyUPP notifier; +#endif + +/* Input: ep - endpointref on which to negotiate the option + enableReuseIPMode - desired option setting - true/false + Return: kOTNoError indicates that the option was successfully negotiated + OSStatus is an error if < 0, otherwise, the status field is + returned and is > 0. + + IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise + this code will not function as desired +*/ + +/* +NOTE: As this version is written async way, we don't use this function... +(010526) masahiro minami +*/ +/* +OSStatus DoNegotiateIPReuseAddrOption(EndpointRef ep, Boolean enableReuseIPMode) + +{ + UInt8 buf[kOTFourByteOptionSize]; // define buffer for fourByte Option size + TOption* opt; // option ptr to make items easier to access + TOptMgmt req; + TOptMgmt ret; + OSStatus err; + + if (!OTIsSynchronous(ep)) + { + return (-1); + } + opt = (TOption*)buf; // set option ptr to buffer + req.opt.buf = buf; + req.opt.len = sizeof(buf); + req.flags = T_NEGOTIATE; // negotiate for option + + ret.opt.buf = buf; + ret.opt.maxlen = kOTFourByteOptionSize; + + opt->level = INET_IP; // dealing with an IP Level function + opt->name = IP_REUSEADDR; + opt->len = kOTFourByteOptionSize; + opt->status = 0; + *(UInt32*)opt->value = enableReuseIPMode; // set the desired option level, true or false + + err = OTOptionManagement(ep, &req, &ret); + + // if no error then return the option status value + if (err == kOTNoError) + { + if (opt->status != T_SUCCESS) + err = opt->status; + else + err = kOTNoError; + } + + return err; +} +*/ + +/* A helper function for Mac OpenTransport support*/ +// This function is a complete copy from GUSI +// ( masahiro minami ) +// ( 01/02/19 ) +static __inline__ Uint32 CompleteMask(OTEventCode code) +{ + return 1 << (code & 0x1F); +} + +/* Notifier for async OT calls */ +static pascal void AsyncTCPNotifier( TCPsocket sock, OTEventCode code, + OTResult result, void* cookie ) +{ + +#ifdef DEBUG_NET + printf("AsyncTCPNotifier got an event : 0x%8.8x\n", code ); +#endif + + switch( code & 0x7f000000L) + { + case 0: + sock->newEvent |= code; + result = 0; + break; + case kCOMPLETEEVENT: + if(!(code & 0x00FFFFE0 )) + sock->newCompletion |= CompleteMask( code ); + if( code == T_OPENCOMPLETE ) + sock->channel = (SOCKET)(cookie); + break; + default: + if( code != kOTProviderWillClose ) + result = 0; + } + // Do we need these ???? TODO + // sock->SetAsyncMacError( result ); + // sock->Wakeup(); +} + +/* Retrieve OT event */ +// This function is taken from GUSI interface. +// ( 01/02/19 masahiro minami ) +static void AsyncTCPPopEvent( TCPsocket sock ) +{ + // Make sure OT calls are not interrupted + // Not sure if we really need this. + OTEnterNotifier( sock->channel ); + + sock->event |= (sock->curEvent = sock->newEvent ); + sock->completion |= ( sock->curCompletion = sock->newCompletion ); + sock->newEvent = sock->newCompletion = 0; + + OTLeaveNotifier( sock->channel ); + + if( sock->curEvent & T_UDERR) + { + // We just clear the error. + // Should we feed this back to users ? + // (TODO ) + OTRcvUDErr( sock->channel, NULL ); + +#ifdef DEBUG_NET + printf("AsyncTCPPopEvent T_UDERR recognized"); +#endif + } + + // Remote is disconnecting... + if( sock->curEvent & ( T_DISCONNECT | T_ORDREL )) + { + sock->readShutdown = true; + } + + if( sock->curEvent &T_CONNECT ) + { + // Ignore the info of remote (second parameter). + // Shoule we care ? + // (TODO) + OTRcvConnect( sock->channel, NULL ); + sock->connected = 1; + } + + if( sock->curEvent & T_ORDREL ) + { + OTRcvOrderlyDisconnect( sock->channel ); + } + + if( sock->curEvent & T_DISCONNECT ) + { + OTRcvDisconnect( sock->channel, NULL ); + } + + // Do we need to ? + // (masahiro minami) + //YieldToAnyThread(); +} + +/* Create a new TCPsocket */ +// Because TCPsocket structure gets bigger and bigger, +// I think we'd better have a constructor function and delete function. +// ( 01/02/25 masahiro minami ) +static TCPsocket AsyncTCPNewSocket() +{ + TCPsocket sock; + + sock = (TCPsocket)malloc(sizeof(*sock)); + if ( sock == NULL ) { + SDLNet_SetError("Out of memory"); + return NULL; + } + + sock->newEvent = 0; + sock->event = 0; + sock->curEvent = 0; + sock->newCompletion = 0; + sock->completion = 0; + sock->curCompletion = 0; + //sock->info = NULL; + sock->readShutdown = sock->writeShutdown = sock->connected = false; + sock->error = 0; + sock->config = NULL; + sock->nextListener = NULL; + sock->sflag = 0; + return sock; +} + +// hmmm.... do we need this ??? +// ( 01/02/25 masahiro minami) +static void AsycnTCPDeleteSocket( TCPsocket sock ) +{ + SDLNet_TCP_Close( sock ); +} +/* Open a TCP network socket + If 'remote' is NULL, this creates a local server socket on the given port, + otherwise a TCP connection to the remote host and port is attempted. + The newly created socket is returned, or NULL if there was an error. + + ( re-written by masahiro minami + Now endpoint is created in Async mode. + 01/02/20 ) +*/ +TCPsocket SDLNet_TCP_Open(IPaddress *ip) +{ + EndpointRef dummy = NULL; + + TCPsocket sock = AsyncTCPNewSocket(); + if( ! sock) + return NULL; + + // Determin whether bind locally, or connect to remote + if ( (ip->host != INADDR_NONE) && (ip->host != INADDR_ANY) ) + { + // ######## Connect to remote + OTResult stat; + InetAddress inAddr; + TBind bindReq; + + // Open endpoint + sock->error = OTAsyncOpenEndpoint( + OTCreateConfiguration(kTCPName), NULL, &(sock->info), + (OTNotifyProcPtr)(AsyncTCPNotifier), + sock ); + + AsyncTCPPopEvent( sock ); + while( !sock->error && !( sock->completion & CompleteMask(T_OPENCOMPLETE))) + { + //SetThreadState( kCurrentThreadID, kReadyThreadState, kNoThreadID ); + //YieldToAnyThread(); + //WaitNextEvent(everyEvent, &macEvent, 1, NULL); + AsyncTCPPopEvent( sock ); + } + + if( !sock->channel ) + { + SDLNet_SetError("OTAsyncOpenEndpoint failed --- client socket could not be opened"); + goto error_return; + } + + // Set blocking mode + // I'm not sure if this is a good solution.... + // Check out Apple's sample code, OT Virtual Server + // ( 010314 masahiro minami) + + sock->error = OTSetBlocking( sock->channel ); + if( sock->error != kOTNoError ) + { + SDLNet_SetError("OTSetBlocking() returned an error"); + goto error_return; + } + + // Bind the socket + OTInitInetAddress(&inAddr, 0, 0 ); + bindReq.addr.len = sizeof( InetAddress ); + bindReq.addr.buf = (unsigned char*)&inAddr; + bindReq.qlen = 0; + + sock->error = OTBind( sock->channel, &bindReq, NULL ); + AsyncTCPPopEvent(sock); + while( !sock->error && !( sock->completion & CompleteMask(T_BINDCOMPLETE))) + { + //YieldToAnyThread(); + //WaitNextEvent(everyEvent, &macEvent, 1, NULL); + AsyncTCPPopEvent(sock); + } + + + switch( stat = OTGetEndpointState( sock->channel )) + { + InetAddress inAddr; + TCall sndCall; + OTResult res; + + case T_OUTCON: + SDLNet_SetError("SDLNet_Open() failed -- T_OUTCON"); + goto error_return; + break; + case T_IDLE: + sock->readShutdown = false; + sock->writeShutdown = false; + sock->event &=~T_CONNECT; + + OTMemzero(&sndCall, sizeof(TCall)); + OTInitInetAddress(&inAddr, ip->port, ip->host ); + sndCall.addr.len = sizeof(InetAddress); + sndCall.addr.buf = (unsigned char*)&inAddr; + sock->connected = 0; + res = OTConnect( sock->channel, &sndCall, NULL ); + AsyncTCPPopEvent(sock); + while( sock->error == kOTNoDataErr || !sock->connected ) + AsyncTCPPopEvent(sock); + break; + default: + // What's to be done ? (TODO) + SDLNet_SetError("SDLNet_TCP_Open() failed -- EndpointState not good"); + goto error_return; + + } + if( !(sock->event & (T_CONNECT|T_DISCONNECT))) + goto error_return; + + AsyncTCPPopEvent( sock ); + while( !(sock->event & (T_CONNECT|T_DISCONNECT))) + { + AsyncTCPPopEvent( sock ); + } + // OTConnect successfull + if( sock->event & T_CONNECT) + { + sock->remoteAddress.host = inAddr.fHost; + sock->remoteAddress.port = inAddr.fPort; + sock->sflag = false; + } + else + { + // OTConnect failed + sock->event &= ~T_DISCONNECT; + goto error_return; + } + } + else + { + // ######## Bind locally + TBind bindReq; + InetAddress inAddr; + + // First, get InetInterfaceInfo. + // I don't search for all of them. + // Does that matter ? + + sock->error = OTAsyncOpenEndpoint( + OTCreateConfiguration("tilisten, tcp"), NULL, &(sock->info), + (OTNotifyProcPtr)(AsyncTCPNotifier), + sock); + AsyncTCPPopEvent( sock ); + while( !sock->error && !( sock->completion & CompleteMask( T_OPENCOMPLETE))) + { + AsyncTCPPopEvent( sock ); + } + + if( ! sock->channel ) + { + SDLNet_SetError("OTAsyncOpenEndpoint failed --- server socket could not be opened"); + goto error_return; + } + + // Create a master OTConfiguration + sock->config = OTCreateConfiguration(kTCPName); + if( ! sock->config ) + { + SDLNet_SetError("Could not create master OTConfiguration"); + goto error_return; + } + + // Bind the socket + OTInitInetAddress(&inAddr, ip->port, 0 ); + inAddr.fAddressType = AF_INET; + bindReq.addr.len = sizeof( InetAddress ); + bindReq.addr.buf = (unsigned char*)&inAddr; + bindReq.qlen = 35; // This number is NOT well considered. (TODO) + sock->localAddress.host = inAddr.fHost; + sock->localAddress.port = inAddr.fPort; + sock->sflag = true; + + sock->error = OTBind( sock->channel, &bindReq, NULL ); + AsyncTCPPopEvent(sock); + while( !sock->error && !( sock->completion & CompleteMask(T_BINDCOMPLETE))) + { + AsyncTCPPopEvent(sock); + } + if( sock->error != kOTNoError ) + { + SDLNet_SetError("Could not bind server socket"); + goto error_return; + } + + if( dummy ) + OTCloseProvider( dummy ); + + } + + sock->ready = 0; + return sock; + + error_return: + if( dummy ) + OTCloseProvider( dummy ); + SDLNet_TCP_Close( sock ); + return NULL; +} + +/* Accept an incoming connection on the given server socket. + The newly created socket is returned, or NULL if there was an error. +*/ +TCPsocket SDLNet_TCP_Accept(TCPsocket server) +{ + + /* Only server sockets can accept */ + if ( ! server->sflag ) { + SDLNet_SetError("Only server sockets can accept()"); + return(NULL); + } + server->ready = 0; + + /* Accept a new TCP connection on a server socket */ + { + InetAddress peer; + TCall peerinfo; + TCPsocket sock = NULL; + Boolean mustListen = false; + OTResult err; + + memset(&peerinfo, 0, (sizeof peerinfo )); + peerinfo.addr.buf = (Uint8 *) &peer; + peerinfo.addr.maxlen = sizeof(peer); + + while( mustListen || !sock ) + { + // OTListen + // We do NOT block ---- right thing ? (TODO) + err = OTListen( server->channel, &peerinfo ); + + if( err ) + goto error_return; + else + { + mustListen = false; + sock = AsyncTCPNewSocket(); + if( ! sock ) + goto error_return; + } + } + if( sock ) + { + // OTAsyncOpenEndpoint + server->error = OTAsyncOpenEndpoint( OTCloneConfiguration( server->config ), + NULL, &(sock->info), (OTNotifyProcPtr)AsyncTCPNotifier, sock ); + AsyncTCPPopEvent( sock ); + while( !sock->error && !( sock->completion & CompleteMask( T_OPENCOMPLETE))) + { + AsyncTCPPopEvent( sock ); + } + if( ! sock->channel ) + { + mustListen = false; + goto error_return; + } + + // OTAccept + server->completion &= ~(CompleteMask(T_ACCEPTCOMPLETE)); + server->error = OTAccept( server->channel, sock->channel, &peerinfo ); + AsyncTCPPopEvent( server ); + while( !(server->completion & CompleteMask(T_ACCEPTCOMPLETE))) + { + AsyncTCPPopEvent( server ); + } + + switch( server->error ) + { + case kOTLookErr: + switch( OTLook(server->channel )) + { + case T_LISTEN: + mustListen = true; + break; + case T_DISCONNECT: + goto error_return; + } + break; + case 0: + sock->nextListener = server->nextListener; + server->nextListener = sock; + sock->remoteAddress.host = peer.fHost; + sock->remoteAddress.port = peer.fPort; + return sock; + // accept successful + break; + default: + free( sock ); + } + } + sock->remoteAddress.host = peer.fHost; + sock->remoteAddress.port = peer.fPort; + sock->sflag = 0; + sock->ready = 0; + + /* The socket is ready */ + return(sock); + + // Error; close the socket and return + error_return: + SDLNet_TCP_Close(sock); + return(NULL); + } +} + +/* Get the IP address of the remote system associated with the socket. + If the socket is a server socket, this function returns NULL. +*/ +IPaddress *SDLNet_TCP_GetPeerAddress(TCPsocket sock) +{ + if ( sock->sflag ) { + return(NULL); + } + return(&sock->remoteAddress); +} + +/* Send 'len' bytes of 'data' over the non-server socket 'sock' + This function returns the actual amount of data sent. If the return value + is less than the amount of data sent, then either the remote connection was + closed, or an unknown socket error occurred. +*/ +int SDLNet_TCP_Send(TCPsocket sock, const void *datap, int len) +{ + const Uint8 *data = (const Uint8 *)datap; /* For pointer arithmetic */ + int sent, left; + + /* Server sockets are for accepting connections only */ + if ( sock->sflag ) { + SDLNet_SetError("Server sockets cannot send"); + return(-1); + } + + /* Keep sending data until it's sent or an error occurs */ + left = len; + sent = 0; + errno = 0; + do { + len = OTSnd(sock->channel, (void *)data, left, 0); + if (len == kOTFlowErr) + len = 0; + if ( len > 0 ) { + sent += len; + left -= len; + data += len; + } + // Do we need to ? + // ( masahiro minami ) + // (TODO) + //WaitNextEvent(everyEvent, &macEvent, 1, NULL); + //AsyncTCPPopEvent(sock); + } while ( (left > 0) && (len > 0) ); + + return(sent); +} + +/* Receive up to 'maxlen' bytes of data over the non-server socket 'sock', + and store them in the buffer pointed to by 'data'. + This function returns the actual amount of data received. If the return + value is less than or equal to zero, then either the remote connection was + closed, or an unknown socket error occurred. +*/ +int SDLNet_TCP_Recv(TCPsocket sock, void *data, int maxlen) +{ + int len = 0; + OSStatus res; + /* Server sockets are for accepting connections only */ + if ( sock->sflag ) { + SDLNet_SetError("Server sockets cannot receive"); + return(-1); + } + + do + { + res = OTRcv(sock->channel, data, maxlen-len, 0); + if (res > 0) { + len = res; + } + +#ifdef DEBUG_NET + if ( res != kOTNoDataErr ) + printf("SDLNet_TCP_Recv received ; %d\n", res ); +#endif + + AsyncTCPPopEvent(sock); + if( res == kOTLookErr ) + { + res = OTLook(sock->channel ); + continue; + } + } while ( (len == 0) && (res == kOTNoDataErr) ); + + sock->ready = 0; + if ( len == 0 ) { /* Open Transport error */ +#ifdef DEBUG_NET + printf("Open Transport error: %d\n", res); +#endif + return(-1); + } + return(len); +} + +/* Close a TCP network socket */ +void SDLNet_TCP_Close(TCPsocket sock) +{ + if ( sock != NULL ) { + if ( sock->channel != INVALID_SOCKET ) { + //closesocket(sock->channel); + OTSndOrderlyDisconnect( sock->channel ); + } + free(sock); + } +} + +#else /* !MACOS_OPENTRANSPORT */ + +struct _TCPsocket { + int ready; + SOCKET channel; + IPaddress remoteAddress; + IPaddress localAddress; + int sflag; +}; + +/* Open a TCP network socket + If 'remote' is NULL, this creates a local server socket on the given port, + otherwise a TCP connection to the remote host and port is attempted. + The newly created socket is returned, or NULL if there was an error. +*/ +TCPsocket SDLNet_TCP_Open(IPaddress *ip) +{ + TCPsocket sock; + struct sockaddr_in sock_addr; + + /* Allocate a TCP socket structure */ + sock = (TCPsocket)malloc(sizeof(*sock)); + if ( sock == NULL ) { + SDLNet_SetError("Out of memory"); + goto error_return; + } + + /* Open the socket */ + sock->channel = socket(AF_INET, SOCK_STREAM, 0); + if ( sock->channel == INVALID_SOCKET ) { + SDLNet_SetError("Couldn't create socket"); + goto error_return; + } + + /* Connect to remote, or bind locally, as appropriate */ + if ( (ip->host != INADDR_NONE) && (ip->host != INADDR_ANY) ) { + + // ######### Connecting to remote + + memset(&sock_addr, 0, sizeof(sock_addr)); + sock_addr.sin_family = AF_INET; + sock_addr.sin_addr.s_addr = ip->host; + sock_addr.sin_port = ip->port; + + /* Connect to the remote host */ + if ( connect(sock->channel, (struct sockaddr *)&sock_addr, + sizeof(sock_addr)) == SOCKET_ERROR ) { + SDLNet_SetError("Couldn't connect to remote host"); + goto error_return; + } + sock->sflag = 0; + } else { + + // ########## Binding locally + + memset(&sock_addr, 0, sizeof(sock_addr)); + sock_addr.sin_family = AF_INET; + sock_addr.sin_addr.s_addr = INADDR_ANY; + sock_addr.sin_port = ip->port; + +/* + * Windows gets bad mojo with SO_REUSEADDR: + * http://www.devolution.com/pipermail/sdl/2005-September/070491.html + * --ryan. + */ +#ifndef WIN32 + /* allow local address reuse */ + { int yes = 1; + setsockopt(sock->channel, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes)); + } +#endif + + /* Bind the socket for listening */ + if ( bind(sock->channel, (struct sockaddr *)&sock_addr, + sizeof(sock_addr)) == SOCKET_ERROR ) { + SDLNet_SetError("Couldn't bind to local port"); + goto error_return; + } + if ( listen(sock->channel, 5) == SOCKET_ERROR ) { + SDLNet_SetError("Couldn't listen to local port"); + goto error_return; + } + + /* Set the socket to non-blocking mode for accept() */ +#if defined(__BEOS__) && defined(SO_NONBLOCK) + /* On BeOS r5 there is O_NONBLOCK but it's for files only */ + { + long b = 1; + setsockopt(sock->channel, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b)); + } +#elif defined(O_NONBLOCK) + { + fcntl(sock->channel, F_SETFL, O_NONBLOCK); + } +#elif defined(WIN32) + { + unsigned long mode = 1; + ioctlsocket (sock->channel, FIONBIO, &mode); + } +#elif defined(__OS2__) + { + int dontblock = 1; + ioctl(sock->channel, FIONBIO, &dontblock); + } +#else +#warning How do we set non-blocking mode on other operating systems? +#endif + sock->sflag = 1; + } + sock->ready = 0; + +#ifdef TCP_NODELAY + /* Set the nodelay TCP option for real-time games */ + { int yes = 1; + setsockopt(sock->channel, IPPROTO_TCP, TCP_NODELAY, (char*)&yes, sizeof(yes)); + } +#endif /* TCP_NODELAY */ + + /* Fill in the channel host address */ + sock->remoteAddress.host = sock_addr.sin_addr.s_addr; + sock->remoteAddress.port = sock_addr.sin_port; + + /* The socket is ready */ + return(sock); + +error_return: + SDLNet_TCP_Close(sock); + return(NULL); +} + +/* Accept an incoming connection on the given server socket. + The newly created socket is returned, or NULL if there was an error. +*/ +TCPsocket SDLNet_TCP_Accept(TCPsocket server) +{ + TCPsocket sock; + struct sockaddr_in sock_addr; + int sock_alen; + + /* Only server sockets can accept */ + if ( ! server->sflag ) { + SDLNet_SetError("Only server sockets can accept()"); + return(NULL); + } + server->ready = 0; + + /* Allocate a TCP socket structure */ + sock = (TCPsocket)malloc(sizeof(*sock)); + if ( sock == NULL ) { + SDLNet_SetError("Out of memory"); + goto error_return; + } + + /* Accept a new TCP connection on a server socket */ + sock_alen = sizeof(sock_addr); + sock->channel = accept(server->channel, (struct sockaddr *)&sock_addr, +#ifdef USE_GUSI_SOCKETS + (unsigned int *)&sock_alen); +#else + &sock_alen); +#endif + if ( sock->channel == SOCKET_ERROR ) { + SDLNet_SetError("accept() failed"); + goto error_return; + } +#ifdef WIN32 + { + /* passing a zero value, socket mode set to block on */ + unsigned long mode = 0; + ioctlsocket (sock->channel, FIONBIO, &mode); + } +#elif defined(O_NONBLOCK) + { + int flags = fcntl(sock->channel, F_GETFL, 0); + fcntl(sock->channel, F_SETFL, flags & ~O_NONBLOCK); + } +#endif /* WIN32 */ + sock->remoteAddress.host = sock_addr.sin_addr.s_addr; + sock->remoteAddress.port = sock_addr.sin_port; + + sock->sflag = 0; + sock->ready = 0; + + /* The socket is ready */ + return(sock); + +error_return: + SDLNet_TCP_Close(sock); + return(NULL); +} + +/* Get the IP address of the remote system associated with the socket. + If the socket is a server socket, this function returns NULL. +*/ +IPaddress *SDLNet_TCP_GetPeerAddress(TCPsocket sock) +{ + if ( sock->sflag ) { + return(NULL); + } + return(&sock->remoteAddress); +} + +/* Send 'len' bytes of 'data' over the non-server socket 'sock' + This function returns the actual amount of data sent. If the return value + is less than the amount of data sent, then either the remote connection was + closed, or an unknown socket error occurred. +*/ +int SDLNet_TCP_Send(TCPsocket sock, const void *datap, int len) +{ + const Uint8 *data = (const Uint8 *)datap; /* For pointer arithmetic */ + int sent, left; + + /* Server sockets are for accepting connections only */ + if ( sock->sflag ) { + SDLNet_SetError("Server sockets cannot send"); + return(-1); + } + + /* Keep sending data until it's sent or an error occurs */ + left = len; + sent = 0; + errno = 0; + do { + len = send(sock->channel, (const char *) data, left, 0); + if ( len > 0 ) { + sent += len; + left -= len; + data += len; + } + } while ( (left > 0) && ((len > 0) || (errno == EINTR)) ); + + return(sent); +} + +/* Receive up to 'maxlen' bytes of data over the non-server socket 'sock', + and store them in the buffer pointed to by 'data'. + This function returns the actual amount of data received. If the return + value is less than or equal to zero, then either the remote connection was + closed, or an unknown socket error occurred. +*/ +int SDLNet_TCP_Recv(TCPsocket sock, void *data, int maxlen) +{ + int len; + + /* Server sockets are for accepting connections only */ + if ( sock->sflag ) { + SDLNet_SetError("Server sockets cannot receive"); + return(-1); + } + + errno = 0; + do { + len = recv(sock->channel, (char *) data, maxlen, 0); + } while ( errno == EINTR ); + + sock->ready = 0; + return(len); +} + +/* Close a TCP network socket */ +void SDLNet_TCP_Close(TCPsocket sock) +{ + if ( sock != NULL ) { + if ( sock->channel != INVALID_SOCKET ) { + closesocket(sock->channel); + } + free(sock); + } +} + +#endif /* MACOS_OPENTRANSPORT */ diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/sdl_net/SDLnetUDP.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/sdl_net/SDLnetUDP.c Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,797 @@ +/* + SDL_net: An example cross-platform network library for use with SDL + Copyright (C) 1997-2004 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/* $Id: SDLnetUDP.c 1192 2004-01-04 17:41:55Z slouken $ */ + +#include "SDLnetsys.h" +#include "SDL_net.h" +#ifdef MACOS_OPENTRANSPORT +#include +#endif + +struct _UDPsocket { + int ready; + SOCKET channel; + IPaddress address; + +#ifdef MACOS_OPENTRANSPORT + OTEventCode newEvent; + OTEventCode event; + OTEventCode curEvent; + OTEventCode newCompletion; + OTEventCode completion; + OTEventCode curCompletion; + TEndpointInfo info; + Boolean readShutdown; + Boolean writeShutdown; + OSStatus error; + OTConfigurationRef config; // Master configuration. you can clone this. +#endif /* MACOS_OPENTRANSPORT */ + + struct UDP_channel { + int numbound; + IPaddress address[SDLNET_MAX_UDPADDRESSES]; + } binding[SDLNET_MAX_UDPCHANNELS]; +}; + +#ifdef MACOS_OPENTRANSPORT + +/* A helper function for Mac OpenTransport support*/ +// This function is a complete copy from GUSI +// ( masahiro minami ) +// ( 01/02/19 ) +// +// I guess this function should be put in SDLnet.c +// ( 010315 masahiro minami) +// (TODO) +static __inline__ Uint32 CompleteMask(OTEventCode code) +{ + return 1 << (code & 0x1F); +} + +/* Notifier for async OT calls */ +// This function is completely same as AsyncTCPNotifier, +// except for the argument, UDPsocket / TCPsocket +// ( 010315 masahiro minami) +static pascal void AsyncUDPNotifier( UDPsocket sock, OTEventCode code, + OTResult result, void* cookie ) +{ + switch( code & 0x7f000000L) + { + case 0: + sock->newEvent |= code; + result = 0; + break; + case kCOMPLETEEVENT: + if(!(code & 0x00FFFFE0 )) + sock->newCompletion |= CompleteMask( code ); + if( code == T_OPENCOMPLETE ) + sock->channel = (SOCKET)(cookie); + break; + default: + if( code != kOTProviderWillClose ) + result = 0; + } + // Do we need these ???? TODO + // sock->SetAsyncMacError( result ); + // sock->Wakeup(); + + // Do we need to ? + //YieldToAnyThread(); +} + +/* Retrieve OT event */ +// This function is completely same as AsyncTCPPopEvent, +// except for the argument, UDPsocket / TCPsocket +// ( 010315 masahiro minami) +static void AsyncUDPPopEvent( UDPsocket sock ) +{ + // Make sure OT calls are not interrupted + // Not sure if we really need this. + OTEnterNotifier( sock->channel ); + + sock->event |= (sock->curEvent = sock->newEvent ); + sock->completion |= ( sock->curCompletion = sock->newCompletion ); + sock->newEvent = sock->newCompletion = 0; + + OTLeaveNotifier( sock->channel ); + + if( sock->curEvent & T_UDERR) + { + // We just clear the error. + // Should we feed this back to users ? + // (TODO ) + OTRcvUDErr( sock->channel, NULL ); + } + + // Remote is disconnecting... + if( sock->curEvent & ( T_DISCONNECT | T_ORDREL )) + { + sock->readShutdown = true; + } + + if( sock->curEvent &T_CONNECT) + { + // Ignore the info of remote (second parameter). + // Shoule we care ? + // (TODO) + OTRcvConnect( sock->channel, NULL ); + } + + if( sock->curEvent & T_ORDREL ) + { + OTRcvOrderlyDisconnect( sock->channel ); + } + + if( sock->curEvent & T_DISCONNECT ) + { + OTRcvDisconnect( sock->channel, NULL ); + } + + // Should we ?? + // (010318 masahiro minami + //YieldToAnyThread(); +} + +/* Create a new UDPsocket */ +// Because TCPsocket structure gets bigger and bigger, +// I think we'd better have a constructor function and delete function. +// ( 01/02/25 masahiro minami ) +/*static*/ UDPsocket AsyncUDPNewSocket() +{ + UDPsocket sock; + + sock = (UDPsocket)malloc(sizeof(*sock)); + if ( sock == NULL ) { + SDLNet_SetError("Out of memory"); + return NULL; + } + + sock->newEvent = 0; + sock->event = 0; + sock->curEvent = 0; + sock->newCompletion = 0; + sock->completion = 0; + sock->curCompletion = 0; + //sock->info = NULL; + sock->readShutdown = sock->writeShutdown = false; + sock->error = 0; + sock->config = NULL; + + return sock; +} + +#endif /* MACOS_OPENTRANSPORT */ + +/* Allocate/free a single UDP packet 'size' bytes long. + The new packet is returned, or NULL if the function ran out of memory. + */ +extern UDPpacket *SDLNet_AllocPacket(int size) +{ + UDPpacket *packet; + int error; + + + error = 1; + packet = (UDPpacket *)malloc(sizeof(*packet)); + if ( packet != NULL ) { + packet->maxlen = size; + packet->data = (Uint8 *)malloc(size); + if ( packet->data != NULL ) { + error = 0; + } + } + if ( error ) { + SDLNet_FreePacket(packet); + packet = NULL; + } + return(packet); +} +int SDLNet_ResizePacket(UDPpacket *packet, int newsize) +{ + Uint8 *newdata; + + newdata = (Uint8 *)malloc(newsize); + if ( newdata != NULL ) { + free(packet->data); + packet->data = newdata; + packet->maxlen = newsize; + } + return(packet->maxlen); +} +extern void SDLNet_FreePacket(UDPpacket *packet) +{ + if ( packet ) { + if ( packet->data ) + free(packet->data); + free(packet); + } +} + +/* Allocate/Free a UDP packet vector (array of packets) of 'howmany' packets, + each 'size' bytes long. + A pointer to the packet array is returned, or NULL if the function ran out + of memory. + */ +UDPpacket **SDLNet_AllocPacketV(int howmany, int size) +{ + UDPpacket **packetV; + + packetV = (UDPpacket **)malloc((howmany+1)*sizeof(*packetV)); + if ( packetV != NULL ) { + int i; + for ( i=0; ierror = OTAsyncOpenEndpoint( + OTCreateConfiguration(kUDPName),0, &(sock->info), + (OTNotifyProcPtr)AsyncUDPNotifier, sock ); + AsyncUDPPopEvent( sock ); + while( !sock->error && !( sock->completion & CompleteMask(T_OPENCOMPLETE))) + { + AsyncUDPPopEvent( sock ); + } + if( sock->error ) + { + SDLNet_SetError("Could not open UDP socket"); + goto error_return; + } + // Should we ?? + // (01/05/03 minami + OTSetBlocking( sock->channel ); + } +#else + sock->channel = socket(AF_INET, SOCK_DGRAM, 0); +#endif /* MACOS_OPENTRANSPORT */ + + if ( sock->channel == INVALID_SOCKET ) + { + SDLNet_SetError("Couldn't create socket"); + goto error_return; + } + +#ifdef MACOS_OPENTRANSPORT + { + InetAddress required, assigned; + TBind req_addr, assigned_addr; + OSStatus status; + InetInterfaceInfo info; + + memset(&assigned_addr, 0, sizeof(assigned_addr)); + assigned_addr.addr.maxlen = sizeof(assigned); + assigned_addr.addr.len = sizeof(assigned); + assigned_addr.addr.buf = (UInt8 *) &assigned; + + if ( port ) { + status = OTInetGetInterfaceInfo( &info, kDefaultInetInterface ); + if( status != kOTNoError ) + goto error_return; + OTInitInetAddress(&required, port, info.fAddress ); + req_addr.addr.maxlen = sizeof( required ); + req_addr.addr.len = sizeof( required ); + req_addr.addr.buf = (UInt8 *) &required; + + sock->error = OTBind(sock->channel, &req_addr, &assigned_addr); + } else { + sock->error = OTBind(sock->channel, nil, &assigned_addr ); + } + AsyncUDPPopEvent(sock); + + while( !sock->error && !(sock->completion & CompleteMask(T_BINDCOMPLETE))) + { + AsyncUDPPopEvent(sock); + } + if (sock->error != noErr) + { + SDLNet_SetError("Couldn't bind to local port, OTBind() = %d",(int) status); + goto error_return; + } + + sock->address.host = assigned.fHost; + sock->address.port = assigned.fPort; + +#ifdef DEBUG_NET + printf("UDP open host = %d, port = %d\n", assigned.fHost, assigned.fPort ); +#endif + } +#else + /* Bind locally, if appropriate */ + if ( port ) + { + struct sockaddr_in sock_addr; + memset(&sock_addr, 0, sizeof(sock_addr)); + sock_addr.sin_family = AF_INET; + sock_addr.sin_addr.s_addr = INADDR_ANY; + sock_addr.sin_port = SDL_SwapBE16(port); + + /* Bind the socket for listening */ + if ( bind(sock->channel, (struct sockaddr *)&sock_addr, + sizeof(sock_addr)) == SOCKET_ERROR ) { + SDLNet_SetError("Couldn't bind to local port"); + goto error_return; + } + /* Fill in the channel host address */ + sock->address.host = sock_addr.sin_addr.s_addr; + sock->address.port = sock_addr.sin_port; + } + +#ifdef SO_BROADCAST + /* Allow LAN broadcasts with the socket */ + { int yes = 1; + setsockopt(sock->channel, SOL_SOCKET, SO_BROADCAST, (char*)&yes, sizeof(yes)); + } +#endif +#endif /* MACOS_OPENTRANSPORT */ + + /* The socket is ready */ + + return(sock); + +error_return: +#ifdef MACOS_OPENTRANSPORT + if( dummy ) + OTCloseProvider( dummy ); +#endif + SDLNet_UDP_Close(sock); + + return(NULL); +} + +/* Verify that the channel is in the valid range */ +static int ValidChannel(int channel) +{ + if ( (channel < 0) || (channel >= SDLNET_MAX_UDPCHANNELS) ) { + SDLNet_SetError("Invalid channel"); + return(0); + } + return(1); +} + +/* Bind the address 'address' to the requested channel on the UDP socket. + If the channel is -1, then the first unbound channel will be bound with + the given address as it's primary address. + If the channel is already bound, this new address will be added to the + list of valid source addresses for packets arriving on the channel. + If the channel is not already bound, then the address becomes the primary + address, to which all outbound packets on the channel are sent. + This function returns the channel which was bound, or -1 on error. +*/ +int SDLNet_UDP_Bind(UDPsocket sock, int channel, IPaddress *address) +{ + struct UDP_channel *binding; + + if ( channel == -1 ) { + for ( channel=0; channel < SDLNET_MAX_UDPCHANNELS; ++channel ) { + binding = &sock->binding[channel]; + if ( binding->numbound < SDLNET_MAX_UDPADDRESSES ) { + break; + } + } + } else { + if ( ! ValidChannel(channel) ) { + return(-1); + } + binding = &sock->binding[channel]; + } + if ( binding->numbound == SDLNET_MAX_UDPADDRESSES ) { + SDLNet_SetError("No room for new addresses"); + return(-1); + } + binding->address[binding->numbound++] = *address; + return(channel); +} + +/* Unbind all addresses from the given channel */ +void SDLNet_UDP_Unbind(UDPsocket sock, int channel) +{ + if ( (channel >= 0) && (channel < SDLNET_MAX_UDPCHANNELS) ) { + sock->binding[channel].numbound = 0; + } +} + +/* Get the primary IP address of the remote system associated with the + socket and channel. + If the channel is not bound, this function returns NULL. + */ +IPaddress *SDLNet_UDP_GetPeerAddress(UDPsocket sock, int channel) +{ + IPaddress *address; + + address = NULL; + switch (channel) { + case -1: + /* Return the actual address of the socket */ + address = &sock->address; + break; + default: + /* Return the address of the bound channel */ + if ( ValidChannel(channel) && + (sock->binding[channel].numbound > 0) ) { + address = &sock->binding[channel].address[0]; + } + break; + } + return(address); +} + +/* Send a vector of packets to the the channels specified within the packet. + If the channel specified in the packet is -1, the packet will be sent to + the address in the 'src' member of the packet. + Each packet will be updated with the status of the packet after it has + been sent, -1 if the packet send failed. + This function returns the number of packets sent. +*/ +int SDLNet_UDP_SendV(UDPsocket sock, UDPpacket **packets, int npackets) +{ + int numsent, i, j; + struct UDP_channel *binding; + int status; +#ifndef MACOS_OPENTRANSPORT + int sock_len; + struct sockaddr_in sock_addr; + + /* Set up the variables to send packets */ + sock_len = sizeof(sock_addr); +#endif + + numsent = 0; + for ( i=0; ichannel < 0 ) + { +#ifdef MACOS_OPENTRANSPORT + TUnitData OTpacket; + InetAddress address; + + memset(&OTpacket, 0, sizeof(OTpacket)); + OTpacket.addr.buf = (Uint8 *)&address; + OTpacket.addr.len = (sizeof address); + OTpacket.udata.buf = packets[i]->data; + OTpacket.udata.len = packets[i]->len; + OTInitInetAddress(&address, packets[i]->address.port, packets[i]->address.host); +#ifdef DEBUG_NET + printf("Packet send address: 0x%8.8x:%d, length = %d\n", packets[i]->address.host, packets[i]->address.port, packets[i]->len); +#endif + + status = OTSndUData(sock->channel, &OTpacket); +#ifdef DEBUG_NET + printf("SDLNet_UDP_SendV OTSndUData return value is ;%d\n", status ); +#endif + + AsyncUDPPopEvent( sock ); + packets[i]->status = status; + + if (status == noErr) + { + ++numsent; + } +#else + sock_addr.sin_addr.s_addr = packets[i]->address.host; + sock_addr.sin_port = packets[i]->address.port; + sock_addr.sin_family = AF_INET; + status = sendto(sock->channel, + packets[i]->data, packets[i]->len, 0, + (struct sockaddr *)&sock_addr,sock_len); + if ( status >= 0 ) + { + packets[i]->status = status; + ++numsent; + } +#endif /* MACOS_OPENTRANSPORT */ + } + else + { + /* Send to each of the bound addresses on the channel */ +#ifdef DEBUG_NET + printf("SDLNet_UDP_SendV sending packet to channel = %d\n", packets[i]->channel ); +#endif + + binding = &sock->binding[packets[i]->channel]; + + for ( j=binding->numbound-1; j>=0; --j ) + { +#ifdef MACOS_OPENTRANSPORT + TUnitData OTpacket; + InetAddress address; + + OTInitInetAddress(&address, binding->address[j].port,binding->address[j].host); +#ifdef DEBUG_NET + printf("Packet send address: 0x%8.8x:%d, length = %d\n", binding->address[j].host, binding->address[j].port, packets[i]->len); +#endif + memset(&OTpacket, 0, sizeof(OTpacket)); + OTpacket.addr.buf = (Uint8 *)&address; + OTpacket.addr.len = (sizeof address); + OTpacket.udata.buf = packets[i]->data; + OTpacket.udata.len = packets[i]->len; + + status = OTSndUData(sock->channel, &OTpacket); +#ifdef DEBUG_NET + printf("SDLNet_UDP_SendV OTSndUData returne value is;%d\n", status ); +#endif + AsyncUDPPopEvent(sock); + packets[i]->status = status; + + if (status == noErr) + { + ++numsent; + } + +#else + sock_addr.sin_addr.s_addr = binding->address[j].host; + sock_addr.sin_port = binding->address[j].port; + sock_addr.sin_family = AF_INET; + status = sendto(sock->channel, + packets[i]->data, packets[i]->len, 0, + (struct sockaddr *)&sock_addr,sock_len); + if ( status >= 0 ) + { + packets[i]->status = status; + ++numsent; + } +#endif /* MACOS_OPENTRANSPORT */ + } + } + } + + return(numsent); +} + +int SDLNet_UDP_Send(UDPsocket sock, int channel, UDPpacket *packet) +{ + /* This is silly, but... */ + packet->channel = channel; + return(SDLNet_UDP_SendV(sock, &packet, 1)); +} + +/* Returns true if a socket is has data available for reading right now */ +static int SocketReady(SOCKET sock) +{ + int retval = 0; +#ifdef MACOS_OPENTRANSPORT + OTResult status; +#else + struct timeval tv; + fd_set mask; +#endif + +#ifdef MACOS_OPENTRANSPORT + //status = OTGetEndpointState(sock); + status = OTLook(sock); + if( status > 0 ) + retval = 1; + +/* switch( status ) + { +// case T_IDLE: + case T_DATAXFER: +// case T_INREL: + retval = 1; + break; + default: + OTCountDataBytes( sock, &numBytes ); + if( numBytes ) + retval = 1; + }*/ +#else + /* Check the file descriptors for available data */ + do { + errno = 0; + + /* Set up the mask of file descriptors */ + FD_ZERO(&mask); + FD_SET(sock, &mask); + + /* Set up the timeout */ + tv.tv_sec = 0; + tv.tv_usec = 0; + + /* Look! */ + retval = select(sock+1, &mask, NULL, NULL, &tv); + } while ( errno == EINTR ); +#endif /* MACOS_OPENTRANSPORT */ + + return(retval == 1); +} + +/* Receive a vector of pending packets from the UDP socket. + The returned packets contain the source address and the channel they arrived + on. If they did not arrive on a bound channel, the the channel will be set + to -1. + This function returns the number of packets read from the network, or -1 + on error. This function does not block, so can return 0 packets pending. +*/ +extern int SDLNet_UDP_RecvV(UDPsocket sock, UDPpacket **packets) +{ + int numrecv, i, j; + struct UDP_channel *binding; +#ifdef MACOS_OPENTRANSPORT + TUnitData OTpacket; + OTFlags flags; + InetAddress address; +#else + int sock_len; + struct sockaddr_in sock_addr; +#endif + + numrecv = 0; + while ( packets[numrecv] && SocketReady(sock->channel) ) + { + UDPpacket *packet; + + packet = packets[numrecv]; + +#ifdef MACOS_OPENTRANSPORT + memset(&OTpacket, 0, sizeof(OTpacket)); + OTpacket.addr.buf = (Uint8 *)&address; + OTpacket.addr.maxlen = (sizeof address); + OTpacket.udata.buf = packet->data; + OTpacket.udata.maxlen = packet->maxlen; + + packet->status = OTRcvUData(sock->channel, &OTpacket, &flags); +#ifdef DEBUG_NET + printf("Packet status: %d\n", packet->status); +#endif + AsyncUDPPopEvent(sock); + if (packet->status == noErr) + { + packet->len = OTpacket.udata.len; + packet->address.host = address.fHost; + packet->address.port = address.fPort; +#ifdef DEBUG_NET + printf("Packet address: 0x%8.8x:%d, length = %d\n", packet->address.host, packet->address.port, packet->len); +#endif + } +#else + sock_len = sizeof(sock_addr); + packet->status = recvfrom(sock->channel, + packet->data, packet->maxlen, 0, + (struct sockaddr *)&sock_addr, +#ifdef USE_GUSI_SOCKETS + (unsigned int *)&sock_len); +#else + &sock_len); +#endif + if ( packet->status >= 0 ) { + packet->len = packet->status; + packet->address.host = sock_addr.sin_addr.s_addr; + packet->address.port = sock_addr.sin_port; + } +#endif + if (packet->status >= 0) + { + packet->channel = -1; + + for (i=(SDLNET_MAX_UDPCHANNELS-1); i>=0; --i ) + { + binding = &sock->binding[i]; + + for ( j=binding->numbound-1; j>=0; --j ) + { + if ( (packet->address.host == binding->address[j].host) && + (packet->address.port == binding->address[j].port) ) + { + packet->channel = i; + goto foundit; /* break twice */ + } + } + } +foundit: + ++numrecv; + } + + else + { + packet->len = 0; + } + } + + sock->ready = 0; + + return(numrecv); +} + +/* Receive a single packet from the UDP socket. + The returned packet contains the source address and the channel it arrived + on. If it did not arrive on a bound channel, the the channel will be set + to -1. + This function returns the number of packets read from the network, or -1 + on error. This function does not block, so can return 0 packets pending. +*/ +int SDLNet_UDP_Recv(UDPsocket sock, UDPpacket *packet) +{ + UDPpacket *packets[2]; + + /* Receive a packet array of 1 */ + packets[0] = packet; + packets[1] = NULL; + return(SDLNet_UDP_RecvV(sock, packets)); +} + +/* Close a UDP network socket */ +extern void SDLNet_UDP_Close(UDPsocket sock) +{ + if ( sock != NULL ) + { + if ( sock->channel != INVALID_SOCKET ) + { +#ifdef MACOS_OPENTRANSPORT + OTUnbind(sock->channel); + OTCloseProvider(sock->channel); +#else + closesocket(sock->channel); +#endif /* MACOS_OPENTRANSPORT */ + } + + free(sock); + } +} + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/sdl_net/SDLnetselect.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/sdl_net/SDLnetselect.c Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,226 @@ +/* + SDL_net: An example cross-platform network library for use with SDL + Copyright (C) 1997-2004 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/* $Id: SDLnetselect.c 1192 2004-01-04 17:41:55Z slouken $ */ + +#include "SDLnetsys.h" +#include "SDL_net.h" + +/* The select() API for network sockets */ + +struct SDLNet_Socket { + int ready; + SOCKET channel; +#ifdef MACOS_OPENTRANSPORT + OTEventCode curEvent; +#endif +}; + +struct _SDLNet_SocketSet { + int numsockets; + int maxsockets; + struct SDLNet_Socket **sockets; +}; + +/* Allocate a socket set for use with SDLNet_CheckSockets() + This returns a socket set for up to 'maxsockets' sockets, or NULL if + the function ran out of memory. + */ +SDLNet_SocketSet SDLNet_AllocSocketSet(int maxsockets) +{ + struct _SDLNet_SocketSet *set; + int i; + + set = (struct _SDLNet_SocketSet *)malloc(sizeof(*set)); + if ( set != NULL ) { + set->numsockets = 0; + set->maxsockets = maxsockets; + set->sockets = (struct SDLNet_Socket **)malloc + (maxsockets*sizeof(*set->sockets)); + if ( set->sockets != NULL ) { + for ( i=0; isockets[i] = NULL; + } + } else { + free(set); + set = NULL; + } + } + return(set); +} + +/* Add a socket to a set of sockets to be checked for available data */ +int SDLNet_AddSocket(SDLNet_SocketSet set, SDLNet_GenericSocket sock) +{ + if ( sock != NULL ) { + if ( set->numsockets == set->maxsockets ) { + SDLNet_SetError("socketset is full"); + return(-1); + } + set->sockets[set->numsockets++] = (struct SDLNet_Socket *)sock; + } + return(set->numsockets); +} + +/* Remove a socket from a set of sockets to be checked for available data */ +int SDLNet_DelSocket(SDLNet_SocketSet set, SDLNet_GenericSocket sock) +{ + int i; + + if ( sock != NULL ) { + for ( i=0; inumsockets; ++i ) { + if ( set->sockets[i] == (struct SDLNet_Socket *)sock ) { + break; + } + } + if ( i == set->numsockets ) { + SDLNet_SetError("socket not found in socketset"); + return(-1); + } + --set->numsockets; + for ( ; inumsockets; ++i ) { + set->sockets[i] = set->sockets[i+1]; + } + } + return(set->numsockets); +} + +/* This function checks to see if data is available for reading on the + given set of sockets. If 'timeout' is 0, it performs a quick poll, + otherwise the function returns when either data is available for + reading, or the timeout in milliseconds has elapsed, which ever occurs + first. This function returns the number of sockets ready for reading, + or -1 if there was an error with the select() system call. +*/ +#ifdef MACOS_OPENTRANSPORT +int SDLNet_CheckSockets(SDLNet_SocketSet set, Uint32 timeout) +{ +Uint32 stop; +int numReady; + + /* Loop, polling the network devices */ + + stop = SDL_GetTicks() + timeout; + + do + { + OTResult status; + size_t numBytes; + int i; + + numReady = 0; + + for (i = set->numsockets-1;i >= 0;--i) + { + status = OTLook( set->sockets[i]->channel ); + if( status > 0 ) + { + switch( status ) + { + case T_UDERR: + OTRcvUDErr( set->sockets[i]->channel , nil); + break; + case T_DISCONNECT: + OTRcvDisconnect( set->sockets[i]->channel, nil ); + break; + case T_ORDREL: + OTRcvOrderlyDisconnect(set->sockets[i]->channel ); + break; + case T_CONNECT: + OTRcvConnect( set->sockets[i]->channel, nil ); + break; + + + default: + set->sockets[i]->ready = 1; + ++numReady; + } + } + else if( OTCountDataBytes(set->sockets[i]->channel, &numBytes ) != kOTNoDataErr ) + { + set->sockets[i]->ready = 1; + ++numReady; + } + else + set->sockets[i]->ready = 0; + } + + } while (!numReady && (SDL_GetTicks() < stop)); + + return(numReady); +} +#else +int SDLNet_CheckSockets(SDLNet_SocketSet set, Uint32 timeout) +{ + int i; + SOCKET maxfd; + int retval; + struct timeval tv; + fd_set mask; + + /* Find the largest file descriptor */ + maxfd = 0; + for ( i=set->numsockets-1; i>=0; --i ) { + if ( set->sockets[i]->channel > maxfd ) { + maxfd = set->sockets[i]->channel; + } + } + + /* Check the file descriptors for available data */ + do { + errno = 0; + + /* Set up the mask of file descriptors */ + FD_ZERO(&mask); + for ( i=set->numsockets-1; i>=0; --i ) { + FD_SET(set->sockets[i]->channel, &mask); + } + + /* Set up the timeout */ + tv.tv_sec = timeout/1000; + tv.tv_usec = (timeout%1000)*1000; + + /* Look! */ + retval = select(maxfd+1, &mask, NULL, NULL, &tv); + } while ( errno == EINTR ); + + /* Mark all file descriptors ready that have data available */ + if ( retval > 0 ) { + for ( i=set->numsockets-1; i>=0; --i ) { + if ( FD_ISSET(set->sockets[i]->channel, &mask) ) { + set->sockets[i]->ready = 1; + } + } + } + return(retval); +} +#endif /* MACOS_OPENTRANSPORT */ + +/* Free a set of sockets allocated by SDL_NetAllocSocketSet() */ +extern void SDLNet_FreeSocketSet(SDLNet_SocketSet set) +{ + if ( set ) { + free(set->sockets); + free(set); + } +} + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/sdl_net/SDLnetsys.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/sdl_net/SDLnetsys.h Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,84 @@ +/* + SDL_net: An example cross-platform network library for use with SDL + Copyright (C) 1997-2004 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/* $Id: SDLnetsys.h 1720 2005-11-23 07:57:10Z icculus $ */ + +/* Include normal system headers */ +#include +#include +#include +#include + +#ifdef macintosh +#ifndef USE_GUSI_SOCKETS +#define MACOS_OPENTRANSPORT +//#error Open Transport driver is broken +#endif +#endif /* macintosh */ + +/* Include system network headers */ +#ifdef MACOS_OPENTRANSPORT +#include +#include +#else +#if defined(__WIN32__) || defined(WIN32) +#define __USE_W32_SOCKETS +#include +#else /* UNIX */ +#ifdef __OS2__ +#include +#include +#endif +#include +#include +#include +#include +#ifndef __BEOS__ +#include +#endif +#ifdef linux /* FIXME: what other platforms have this? */ +#include +#endif +#include +#include +#endif /* WIN32 */ +#endif /* Open Transport */ + +/* System-dependent definitions */ +#ifdef MACOS_OPENTRANSPORT +//#define closesocket OTCloseProvider +#define closesocket OTSndOrderlyDisconnect +#define SOCKET EndpointRef +#define INVALID_SOCKET kOTInvalidEndpointRef +#else +#ifndef __USE_W32_SOCKETS +#ifdef __OS2__ +#define closesocket soclose +#else /* !__OS2__ */ +#define closesocket close +#endif /* __OS2__ */ +#define SOCKET int +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#endif /* __USE_W32_SOCKETS */ +#endif /* Open Transport */ + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/sdl_net/include/SDL_net.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/sdl_net/include/SDL_net.h Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,444 @@ +/* + SDL_net: An example cross-platform network library for use with SDL + Copyright (C) 1997-2004 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/* $Id: SDL_net.h 3281 2007-07-15 05:58:56Z slouken $ */ + +#ifndef _SDL_NET_H +#define _SDL_NET_H + +#include "SDL.h" +#include "SDL_endian.h" +#include "SDL_version.h" +#include "begin_code.h" + + + +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL +*/ +#define SDL_NET_MAJOR_VERSION 1 +#define SDL_NET_MINOR_VERSION 2 +#define SDL_NET_PATCHLEVEL 7 + +/* This macro can be used to fill a version structure with the compile-time + * version of the SDL_net library. + */ +#define SDL_NET_VERSION(X) \ +{ \ + (X)->major = SDL_NET_MAJOR_VERSION; \ + (X)->minor = SDL_NET_MINOR_VERSION; \ + (X)->patch = SDL_NET_PATCHLEVEL; \ +} + +/* This function gets the version of the dynamically linked SDL_net library. + it should NOT be used to fill a version structure, instead you should + use the SDL_NET_VERSION() macro. + */ +extern DECLSPEC const SDL_version * SDLCALL SDLNet_Linked_Version(void); + +/* Initialize/Cleanup the network API + SDL must be initialized before calls to functions in this library, + because this library uses utility functions from the SDL library. +*/ +extern DECLSPEC int SDLCALL SDLNet_Init(void); +extern DECLSPEC void SDLCALL SDLNet_Quit(void); + +/***********************************************************************/ +/* IPv4 hostname resolution API */ +/***********************************************************************/ + +typedef struct { + Uint32 host; /* 32-bit IPv4 host address */ + Uint16 port; /* 16-bit protocol port */ +} IPaddress; + +/* Resolve a host name and port to an IP address in network form. + If the function succeeds, it will return 0. + If the host couldn't be resolved, the host portion of the returned + address will be INADDR_NONE, and the function will return -1. + If 'host' is NULL, the resolved host will be set to INADDR_ANY. + */ +#ifndef INADDR_ANY +#define INADDR_ANY 0x00000000 +#endif +#ifndef INADDR_NONE +#define INADDR_NONE 0xFFFFFFFF +#endif +#ifndef INADDR_BROADCAST +#define INADDR_BROADCAST 0xFFFFFFFF +#endif +extern DECLSPEC int SDLCALL SDLNet_ResolveHost(IPaddress *address, const char *host, Uint16 port); + +/* Resolve an ip address to a host name in canonical form. + If the ip couldn't be resolved, this function returns NULL, + otherwise a pointer to a static buffer containing the hostname + is returned. Note that this function is not thread-safe. +*/ +extern DECLSPEC const char * SDLCALL SDLNet_ResolveIP(IPaddress *ip); + + +/***********************************************************************/ +/* TCP network API */ +/***********************************************************************/ + +typedef struct _TCPsocket *TCPsocket; + +/* Open a TCP network socket + If ip.host is INADDR_NONE or INADDR_ANY, this creates a local server + socket on the given port, otherwise a TCP connection to the remote + host and port is attempted. The address passed in should already be + swapped to network byte order (addresses returned from + SDLNet_ResolveHost() are already in the correct form). + The newly created socket is returned, or NULL if there was an error. +*/ +extern DECLSPEC TCPsocket SDLCALL SDLNet_TCP_Open(IPaddress *ip); + +/* Accept an incoming connection on the given server socket. + The newly created socket is returned, or NULL if there was an error. +*/ +extern DECLSPEC TCPsocket SDLCALL SDLNet_TCP_Accept(TCPsocket server); + +/* Get the IP address of the remote system associated with the socket. + If the socket is a server socket, this function returns NULL. +*/ +extern DECLSPEC IPaddress * SDLCALL SDLNet_TCP_GetPeerAddress(TCPsocket sock); + +/* Send 'len' bytes of 'data' over the non-server socket 'sock' + This function returns the actual amount of data sent. If the return value + is less than the amount of data sent, then either the remote connection was + closed, or an unknown socket error occurred. +*/ +extern DECLSPEC int SDLCALL SDLNet_TCP_Send(TCPsocket sock, const void *data, + int len); + +/* Receive up to 'maxlen' bytes of data over the non-server socket 'sock', + and store them in the buffer pointed to by 'data'. + This function returns the actual amount of data received. If the return + value is less than or equal to zero, then either the remote connection was + closed, or an unknown socket error occurred. +*/ +extern DECLSPEC int SDLCALL SDLNet_TCP_Recv(TCPsocket sock, void *data, int maxlen); + +/* Close a TCP network socket */ +extern DECLSPEC void SDLCALL SDLNet_TCP_Close(TCPsocket sock); + + +/***********************************************************************/ +/* UDP network API */ +/***********************************************************************/ + +/* The maximum channels on a a UDP socket */ +#define SDLNET_MAX_UDPCHANNELS 32 +/* The maximum addresses bound to a single UDP socket channel */ +#define SDLNET_MAX_UDPADDRESSES 4 + +typedef struct _UDPsocket *UDPsocket; +typedef struct { + int channel; /* The src/dst channel of the packet */ + Uint8 *data; /* The packet data */ + int len; /* The length of the packet data */ + int maxlen; /* The size of the data buffer */ + int status; /* packet status after sending */ + IPaddress address; /* The source/dest address of an incoming/outgoing packet */ +} UDPpacket; + +/* Allocate/resize/free a single UDP packet 'size' bytes long. + The new packet is returned, or NULL if the function ran out of memory. + */ +extern DECLSPEC UDPpacket * SDLCALL SDLNet_AllocPacket(int size); +extern DECLSPEC int SDLCALL SDLNet_ResizePacket(UDPpacket *packet, int newsize); +extern DECLSPEC void SDLCALL SDLNet_FreePacket(UDPpacket *packet); + +/* Allocate/Free a UDP packet vector (array of packets) of 'howmany' packets, + each 'size' bytes long. + A pointer to the first packet in the array is returned, or NULL if the + function ran out of memory. + */ +extern DECLSPEC UDPpacket ** SDLCALL SDLNet_AllocPacketV(int howmany, int size); +extern DECLSPEC void SDLCALL SDLNet_FreePacketV(UDPpacket **packetV); + + +/* Open a UDP network socket + If 'port' is non-zero, the UDP socket is bound to a local port. + The 'port' should be given in native byte order, but is used + internally in network (big endian) byte order, in addresses, etc. + This allows other systems to send to this socket via a known port. +*/ +extern DECLSPEC UDPsocket SDLCALL SDLNet_UDP_Open(Uint16 port); + +/* Bind the address 'address' to the requested channel on the UDP socket. + If the channel is -1, then the first unbound channel will be bound with + the given address as it's primary address. + If the channel is already bound, this new address will be added to the + list of valid source addresses for packets arriving on the channel. + If the channel is not already bound, then the address becomes the primary + address, to which all outbound packets on the channel are sent. + This function returns the channel which was bound, or -1 on error. +*/ +extern DECLSPEC int SDLCALL SDLNet_UDP_Bind(UDPsocket sock, int channel, IPaddress *address); + +/* Unbind all addresses from the given channel */ +extern DECLSPEC void SDLCALL SDLNet_UDP_Unbind(UDPsocket sock, int channel); + +/* Get the primary IP address of the remote system associated with the + socket and channel. If the channel is -1, then the primary IP port + of the UDP socket is returned -- this is only meaningful for sockets + opened with a specific port. + If the channel is not bound and not -1, this function returns NULL. + */ +extern DECLSPEC IPaddress * SDLCALL SDLNet_UDP_GetPeerAddress(UDPsocket sock, int channel); + +/* Send a vector of packets to the the channels specified within the packet. + If the channel specified in the packet is -1, the packet will be sent to + the address in the 'src' member of the packet. + Each packet will be updated with the status of the packet after it has + been sent, -1 if the packet send failed. + This function returns the number of packets sent. +*/ +extern DECLSPEC int SDLCALL SDLNet_UDP_SendV(UDPsocket sock, UDPpacket **packets, int npackets); + +/* Send a single packet to the specified channel. + If the channel specified in the packet is -1, the packet will be sent to + the address in the 'src' member of the packet. + The packet will be updated with the status of the packet after it has + been sent. + This function returns 1 if the packet was sent, or 0 on error. + + NOTE: + The maximum size of the packet is limited by the MTU (Maximum Transfer Unit) + of the transport medium. It can be as low as 250 bytes for some PPP links, + and as high as 1500 bytes for ethernet. +*/ +extern DECLSPEC int SDLCALL SDLNet_UDP_Send(UDPsocket sock, int channel, UDPpacket *packet); + +/* Receive a vector of pending packets from the UDP socket. + The returned packets contain the source address and the channel they arrived + on. If they did not arrive on a bound channel, the the channel will be set + to -1. + The channels are checked in highest to lowest order, so if an address is + bound to multiple channels, the highest channel with the source address + bound will be returned. + This function returns the number of packets read from the network, or -1 + on error. This function does not block, so can return 0 packets pending. +*/ +extern DECLSPEC int SDLCALL SDLNet_UDP_RecvV(UDPsocket sock, UDPpacket **packets); + +/* Receive a single packet from the UDP socket. + The returned packet contains the source address and the channel it arrived + on. If it did not arrive on a bound channel, the the channel will be set + to -1. + The channels are checked in highest to lowest order, so if an address is + bound to multiple channels, the highest channel with the source address + bound will be returned. + This function returns the number of packets read from the network, or -1 + on error. This function does not block, so can return 0 packets pending. +*/ +extern DECLSPEC int SDLCALL SDLNet_UDP_Recv(UDPsocket sock, UDPpacket *packet); + +/* Close a UDP network socket */ +extern DECLSPEC void SDLCALL SDLNet_UDP_Close(UDPsocket sock); + + +/***********************************************************************/ +/* Hooks for checking sockets for available data */ +/***********************************************************************/ + +typedef struct _SDLNet_SocketSet *SDLNet_SocketSet; + +/* Any network socket can be safely cast to this socket type */ +typedef struct { + int ready; +} *SDLNet_GenericSocket; + +/* Allocate a socket set for use with SDLNet_CheckSockets() + This returns a socket set for up to 'maxsockets' sockets, or NULL if + the function ran out of memory. + */ +extern DECLSPEC SDLNet_SocketSet SDLCALL SDLNet_AllocSocketSet(int maxsockets); + +/* Add a socket to a set of sockets to be checked for available data */ +#define SDLNet_TCP_AddSocket(set, sock) \ + SDLNet_AddSocket(set, (SDLNet_GenericSocket)sock) +#define SDLNet_UDP_AddSocket(set, sock) \ + SDLNet_AddSocket(set, (SDLNet_GenericSocket)sock) +extern DECLSPEC int SDLCALL SDLNet_AddSocket(SDLNet_SocketSet set, SDLNet_GenericSocket sock); + +/* Remove a socket from a set of sockets to be checked for available data */ +#define SDLNet_TCP_DelSocket(set, sock) \ + SDLNet_DelSocket(set, (SDLNet_GenericSocket)sock) +#define SDLNet_UDP_DelSocket(set, sock) \ + SDLNet_DelSocket(set, (SDLNet_GenericSocket)sock) +extern DECLSPEC int SDLCALL SDLNet_DelSocket(SDLNet_SocketSet set, SDLNet_GenericSocket sock); + +/* This function checks to see if data is available for reading on the + given set of sockets. If 'timeout' is 0, it performs a quick poll, + otherwise the function returns when either data is available for + reading, or the timeout in milliseconds has elapsed, which ever occurs + first. This function returns the number of sockets ready for reading, + or -1 if there was an error with the select() system call. +*/ +extern DECLSPEC int SDLCALL SDLNet_CheckSockets(SDLNet_SocketSet set, Uint32 timeout); + +/* After calling SDLNet_CheckSockets(), you can use this function on a + socket that was in the socket set, to find out if data is available + for reading. +*/ +#define SDLNet_SocketReady(sock) \ + ((sock != NULL) && ((SDLNet_GenericSocket)sock)->ready) + +/* Free a set of sockets allocated by SDL_NetAllocSocketSet() */ +extern DECLSPEC void SDLCALL SDLNet_FreeSocketSet(SDLNet_SocketSet set); + + +/***********************************************************************/ +/* Platform-independent data conversion functions */ +/***********************************************************************/ + +/* Write a 16/32 bit value to network packet buffer */ +extern DECLSPEC void SDLCALL SDLNet_Write16(Uint16 value, void *area); +extern DECLSPEC void SDLCALL SDLNet_Write32(Uint32 value, void *area); + +/* Read a 16/32 bit value from network packet buffer */ +extern DECLSPEC Uint16 SDLCALL SDLNet_Read16(void *area); +extern DECLSPEC Uint32 SDLCALL SDLNet_Read32(void *area); + +/***********************************************************************/ +/* Error reporting functions */ +/***********************************************************************/ + +/* We'll use SDL's functions for error reporting */ +#define SDLNet_SetError SDL_SetError +#define SDLNet_GetError SDL_GetError + +/* I'm eventually going to try to disentangle SDL_net from SDL, thus making + SDL_net an independent X-platform networking toolkit. Not today though.... + +extern no_parse_DECLSPEC void SDLCALL SDLNet_SetError(const char *fmt, ...); +extern no_parse_DECLSPEC char * SDLCALL SDLNet_GetError(void); +*/ + + +/* Inline macro functions to read/write network data */ + +/* Warning, some systems have data access alignment restrictions */ +#if defined(sparc) || defined(mips) +#define SDL_DATA_ALIGNED 1 +#endif +#ifndef SDL_DATA_ALIGNED +#define SDL_DATA_ALIGNED 0 +#endif + +/* Write a 16 bit value to network packet buffer */ +#if !SDL_DATA_ALIGNED +#define SDLNet_Write16(value, areap) \ + (*(Uint16 *)(areap) = SDL_SwapBE16(value)) +#else +#if SDL_BYTEORDER == SDL_BIG_ENDIAN +#define SDLNet_Write16(value, areap) \ +do \ +{ \ + Uint8 *area = (Uint8 *)(areap); \ + area[0] = (value >> 8) & 0xFF; \ + area[1] = value & 0xFF; \ +} while ( 0 ) +#else +#define SDLNet_Write16(value, areap) \ +do \ +{ \ + Uint8 *area = (Uint8 *)(areap); \ + area[1] = (value >> 8) & 0xFF; \ + area[0] = value & 0xFF; \ +} while ( 0 ) +#endif +#endif /* !SDL_DATA_ALIGNED */ + +/* Write a 32 bit value to network packet buffer */ +#if !SDL_DATA_ALIGNED +#define SDLNet_Write32(value, areap) \ + *(Uint32 *)(areap) = SDL_SwapBE32(value); +#else +#if SDL_BYTEORDER == SDL_BIG_ENDIAN +#define SDLNet_Write32(value, areap) \ +do \ +{ \ + Uint8 *area = (Uint8 *)(areap); \ + area[0] = (value >> 24) & 0xFF; \ + area[1] = (value >> 16) & 0xFF; \ + area[2] = (value >> 8) & 0xFF; \ + area[3] = value & 0xFF; \ +} while ( 0 ) +#else +#define SDLNet_Write32(value, areap) \ +do \ +{ \ + Uint8 *area = (Uint8 *)(areap); \ + area[3] = (value >> 24) & 0xFF; \ + area[2] = (value >> 16) & 0xFF; \ + area[1] = (value >> 8) & 0xFF; \ + area[0] = value & 0xFF; \ +} while ( 0 ) +#endif +#endif /* !SDL_DATA_ALIGNED */ + +/* Read a 16 bit value from network packet buffer */ +#if !SDL_DATA_ALIGNED +#define SDLNet_Read16(areap) \ + (SDL_SwapBE16(*(Uint16 *)(areap))) +#else +#if SDL_BYTEORDER == SDL_BIG_ENDIAN +#define SDLNet_Read16(areap) \ + ((((Uint8 *)areap)[0] << 8) | ((Uint8 *)areap)[1] << 0) +#else +#define SDLNet_Read16(areap) \ + ((((Uint8 *)areap)[1] << 8) | ((Uint8 *)areap)[0] << 0) +#endif +#endif /* !SDL_DATA_ALIGNED */ + +/* Read a 32 bit value from network packet buffer */ +#if !SDL_DATA_ALIGNED +#define SDLNet_Read32(areap) \ + (SDL_SwapBE32(*(Uint32 *)(areap))) +#else +#if SDL_BYTEORDER == SDL_BIG_ENDIAN +#define SDLNet_Read32(areap) \ + ((((Uint8 *)areap)[0] << 24) | (((Uint8 *)areap)[1] << 16) | \ + (((Uint8 *)areap)[2] << 8) | ((Uint8 *)areap)[3] << 0) +#else +#define SDLNet_Read32(areap) \ + ((((Uint8 *)areap)[3] << 24) | (((Uint8 *)areap)[2] << 16) | \ + (((Uint8 *)areap)[1] << 8) | ((Uint8 *)areap)[0] << 0) +#endif +#endif /* !SDL_DATA_ALIGNED */ + +#ifdef MACOS_OPENTRANSPORT +#endif +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_NET_H */ diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/src/Android.mk --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/src/Android.mk Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,17 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := main + +LOCAL_C_INCLUDES := $(LOCAL_PATH)/../SDL/include + +# Add your application source files here... +LOCAL_SRC_FILES := ../SDL/src/main/android/SDL_android_main.cpp hedgewars_main.c + +LOCAL_SHARED_LIBRARIES := SDL + +LOCAL_LDLIBS := -llog -lGLESv1_CM + +include $(BUILD_SHARED_LIBRARY) + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/jni/src/hedgewars_main.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/jni/src/hedgewars_main.c Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,40 @@ + +#include "android/log.h" +#include "SDL.h" +#include "dlfcn.h" +#include "GLES/gl.h" + +#define TAG "HWEngine Loader" + +typedef (*HWEngine_Game)(char**); + +main(int argc, char *argv[]){ + void *handle; + char *error; + HWEngine_Game Game; + + + __android_log_print(ANDROID_LOG_INFO, TAG, "HWEngine being loaded"); + handle = dlopen("libhwengine.so", RTLD_NOW|RTLD_GLOBAL); + if(!handle){ + __android_log_print(ANDROID_LOG_INFO, "foo", dlerror()); + __android_log_print(ANDROID_LOG_INFO, "foo", "error dlopen"); + exit(EXIT_FAILURE); + } + dlerror(); + + __android_log_print(ANDROID_LOG_INFO, TAG, "HWEngine successfully loaded.."); + + + Game = (HWEngine_Game) dlsym(handle,"Game"); + if((error = dlerror()) != NULL){ + __android_log_print(ANDROID_LOG_INFO, "foo", error); + __android_log_print(ANDROID_LOG_INFO, "foo", "error dlsym"); + exit(EXIT_FAILURE); + } + __android_log_print(ANDROID_LOG_INFO, "foo", "dlsym succeeded"); + Game(argv); + __android_log_print(ANDROID_LOG_INFO, "foo", "Game() succeeded"); + + dlclose(handle); +} diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-large-mdpi/background.png Binary file project_files/Android-build/SDL-android-project/res/drawable-large-mdpi/background.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-large-mdpi/icon.png Binary file project_files/Android-build/SDL-android-project/res/drawable-large-mdpi/icon.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/backbutton.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/backbutton.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/background.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/background.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/bot1.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/bot1.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/bot2.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/bot2.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/bot3.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/bot3.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/bot4.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/bot4.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/bot5.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/bot5.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/box.9.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/box.9.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/dice.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/dice.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/dropdown.9.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/dropdown.9.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/edit.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/edit.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/fort.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/fort.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/human.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/human.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/icon.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/icon.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/playsound.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/playsound.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/savebutton.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/savebutton.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/settings.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/settings.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/startgamebutton.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/startgamebutton.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/statusbar.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/statusbar.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount.xml Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount0.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount0.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount1.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount1.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount2.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount2.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount3.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount3.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount4.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount4.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount5.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount5.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount6.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount6.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount7.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount7.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount8.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount8.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount9.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teamcount9.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number0.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number0.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number1.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number1.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number2.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number2.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number3.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number3.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number4.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number4.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number5.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number5.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number6.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number6.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number7.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number7.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number8.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number8.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number9.png Binary file project_files/Android-build/SDL-android-project/res/drawable-mdpi/teams_number9.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-normal-hdpi/background.png Binary file project_files/Android-build/SDL-android-project/res/drawable-normal-hdpi/background.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-normal-hdpi/fort.png Binary file project_files/Android-build/SDL-android-project/res/drawable-normal-hdpi/fort.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-normal-hdpi/icon.png Binary file project_files/Android-build/SDL-android-project/res/drawable-normal-hdpi/icon.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-normal-ldpi/icon.png Binary file project_files/Android-build/SDL-android-project/res/drawable-normal-ldpi/icon.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/drawable-xlarge-mdpi/background.png Binary file project_files/Android-build/SDL-android-project/res/drawable-xlarge-mdpi/background.png has changed diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/layout/backbutton.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/res/layout/backbutton.xml Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,13 @@ + + + + \ No newline at end of file diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/layout/background.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/res/layout/background.xml Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/layout/config.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/res/layout/config.xml Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,12 @@ + + + + + + + diff -r f906f6645e02 -r 2e5835130d9a project_files/Android-build/SDL-android-project/res/layout/download.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/res/layout/download.xml Fri Sep 09 05:15:45 2011 +0200 @@ -0,0 +1,40 @@ + + + + +