From: <ror...@us...> - 2007-07-28 00:33:41
|
Revision: 140 http://roreditor.svn.sourceforge.net/roreditor/?rev=140&view=rev Author: rorthomas Date: 2007-07-27 17:33:39 -0700 (Fri, 27 Jul 2007) Log Message: ----------- * updated installer * renamed all .pyw back to .py due to problems Modified Paths: -------------- trunk/devtools/setup/readme-installer.txt trunk/devtools/setup/setup.nsi trunk/lib/ror/svn.py trunk/tools/modtool.py trunk/tools/update.py Added Paths: ----------- trunk/rortoolkit.py trunk/terraineditor.py trunk/truckeditor.py Removed Paths: ------------- trunk/rortoolkit.pyw trunk/terraineditor.pyw trunk/truckeditor.pyw Modified: trunk/devtools/setup/readme-installer.txt =================================================================== --- trunk/devtools/setup/readme-installer.txt 2007-07-27 19:19:31 UTC (rev 139) +++ trunk/devtools/setup/readme-installer.txt 2007-07-28 00:33:39 UTC (rev 140) @@ -1,2 +1,8 @@ have fun and report bugs and feature requests! :) -http://forum.rigsofrods.com \ No newline at end of file +http://forum.rigsofrods.com + +RoR Toolkit Thread: +http://forum.rigsofrods.com/index.php/topic,682.msg5932.html#msg5932 + +RoR Toolkit at the Wiki: +http://wiki.rigsofrods.com/index.php?title=RoRToolkit \ No newline at end of file Modified: trunk/devtools/setup/setup.nsi =================================================================== --- trunk/devtools/setup/setup.nsi 2007-07-27 19:19:31 UTC (rev 139) +++ trunk/devtools/setup/setup.nsi 2007-07-28 00:33:39 UTC (rev 140) @@ -196,7 +196,7 @@ WriteRegStr HKCR "RoRRepo" "URL Protocol" "" WriteRegStr HKCR "RoRRepo\shell" "" "" WriteRegStr HKCR "RoRRepo\shell\open" "" "" - WriteRegStr HKCR 'RoRRepo\shell\open\command' '' '"c:\python25\pythonw.exe" "$INSTDIR\tools\modgui.py installrepo" "%1"' + WriteRegStr HKCR 'RoRRepo\shell\open\command' '' '"%systemdrive%\python25\pythonw.exe" "$INSTDIR\tools\modgui.py installrepo" "%1"' Banner::destroy FunctionEnd @@ -220,6 +220,7 @@ SectionEnd Section /o "Optional Tools" SEC03 + AddSize 20000 SectionIn 1 Call InstallPyWin32 Call InstallPyParsing @@ -230,7 +231,7 @@ SectionIn 1 2 RO SetOutPath "$INSTDIR" SetOverwrite try - File /r /x *.pyc /x ..\..\tools\3rdparty /x ..\..\downloaded /x ..\..\graphs /x .. ..\..\* + File /r /x *.pyc /x doc /x devtools /x 3rdparty /x downloaded /x graphs ..\..\* SectionEnd @@ -242,18 +243,19 @@ !insertmacro MUI_FUNCTION_DESCRIPTION_END Function "LaunchPostInstallation" - ExecWait '"$INSTDIR\update.bat"' - ExecWait '"$INSTDIR\rortoolkit.bat"' + ExecWait "$INSTDIR\tools\update.py" + ExecWait "%systemdrive%\python25\pythonw.exe $INSTDIR\rortoolkit.py" FunctionEnd Section -AdditionalIcons SetOutPath $INSTDIR WriteIniStr "$INSTDIR\${PRODUCT_NAME}.url" "InternetShortcut" "URL" "${PRODUCT_WEB_SITE}" CreateDirectory "$SMPROGRAMS\RoRToolkit" -# CreateShortCut "$SMPROGRAMS\RoRToolkit\RoR Truck Editor.lnk" "$INSTDIR\terraineditor.bat" "" "$INSTDIR\ror.ico" - CreateShortCut "$SMPROGRAMS\RoRToolkit\RoR Toolkit.lnk" "%systemdrive%\python25\pythonw.exe $INSTDIR\rortoolkit.pyw" "" "$INSTDIR\ror.ico" CreateShortCut "$SMPROGRAMS\RoRToolkit\Website.lnk" "$INSTDIR\${PRODUCT_NAME}.url" CreateShortCut "$SMPROGRAMS\RoRToolkit\Uninstall.lnk" "$INSTDIR\uninst.exe" + CreateShortCut '$SMPROGRAMS\RoRToolkit\RoR Terrain Editor.lnk' '"%systemdrive%\python25\pythonw.exe" "$INSTDIR\terraineditor.py"' '' '$INSTDIR\ror.ico' + CreateShortCut '$SMPROGRAMS\RoRToolkit\RoR Truck Editor.lnk' '"%systemdrive%\python25\pythonw.exe" "$INSTDIR\truckeditor.py"' '' '$INSTDIR\ror.ico' + CreateShortCut '$SMPROGRAMS\RoRToolkit\RoR Toolkit.lnk' '"%systemdrive%\python25\pythonw.exe" "$INSTDIR\rortoolkit.py"' '' '$INSTDIR\ror.ico' SectionEnd Section -Post Modified: trunk/lib/ror/svn.py =================================================================== --- trunk/lib/ror/svn.py 2007-07-27 19:19:31 UTC (rev 139) +++ trunk/lib/ror/svn.py 2007-07-28 00:33:39 UTC (rev 140) @@ -78,6 +78,7 @@ try: client = pysvn.Client() + log().info("svn update on this path: %s" % path) # try to restore previous broken updates try: client.cleanup(path) @@ -87,7 +88,7 @@ pass try: - client.resolved(path, reverse=True) + client.resolved(path) except Exception, err: log().error("Error while svn resolved:") log().error(str(err)) Copied: trunk/rortoolkit.py (from rev 135, trunk/rortoolkit.pyw) =================================================================== --- trunk/rortoolkit.py (rev 0) +++ trunk/rortoolkit.py 2007-07-28 00:33:39 UTC (rev 140) @@ -0,0 +1,25 @@ +#Thomas Fischer 31/05/2007, th...@th... +import sys, os, os.path + +def main(): + """ + main method + """ + + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) + + # Import Psyco if available + try: + import psyco + #psyco.full() + #psyco.log() + #psyco.profile() + except ImportError: + pass + + import ror.starter + ror.starter.startApp() + + +if __name__=="__main__": + main() \ No newline at end of file Deleted: trunk/rortoolkit.pyw =================================================================== --- trunk/rortoolkit.pyw 2007-07-27 19:19:31 UTC (rev 139) +++ trunk/rortoolkit.pyw 2007-07-28 00:33:39 UTC (rev 140) @@ -1,25 +0,0 @@ -#Thomas Fischer 31/05/2007, th...@th... -import sys, os, os.path - -def main(): - """ - main method - """ - - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) - - # Import Psyco if available - try: - import psyco - #psyco.full() - #psyco.log() - #psyco.profile() - except ImportError: - pass - - import ror.starter - ror.starter.startApp() - - -if __name__=="__main__": - main() \ No newline at end of file Copied: trunk/terraineditor.py (from rev 135, trunk/terraineditor.pyw) =================================================================== --- trunk/terraineditor.py (rev 0) +++ trunk/terraineditor.py 2007-07-28 00:33:39 UTC (rev 140) @@ -0,0 +1,28 @@ +#Thomas Fischer 31/05/2007, th...@th... +import sys, os, os.path + +def main(): + """ + main method + """ + + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) + import ror.settingsManager + path = ror.settingsManager.getSettingsManager().getSetting("RigsOfRods", "BasePath") + if not os.path.isfile(os.path.join(path,"RoR.exe")): + import ror.starter + ror.starter.startApp() + + # Import Psyco if available + try: + import psyco + psyco.full() + except ImportError: + pass + + import rorterraineditor.MainFrame + rorterraineditor.MainFrame.startApp() + + +if __name__=="__main__": + main() \ No newline at end of file Deleted: trunk/terraineditor.pyw =================================================================== --- trunk/terraineditor.pyw 2007-07-27 19:19:31 UTC (rev 139) +++ trunk/terraineditor.pyw 2007-07-28 00:33:39 UTC (rev 140) @@ -1,28 +0,0 @@ -#Thomas Fischer 31/05/2007, th...@th... -import sys, os, os.path - -def main(): - """ - main method - """ - - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) - import ror.settingsManager - path = ror.settingsManager.getSettingsManager().getSetting("RigsOfRods", "BasePath") - if not os.path.isfile(os.path.join(path,"RoR.exe")): - import ror.starter - ror.starter.startApp() - - # Import Psyco if available - try: - import psyco - psyco.full() - except ImportError: - pass - - import rorterraineditor.MainFrame - rorterraineditor.MainFrame.startApp() - - -if __name__=="__main__": - main() \ No newline at end of file Modified: trunk/tools/modtool.py =================================================================== --- trunk/tools/modtool.py 2007-07-27 19:19:31 UTC (rev 139) +++ trunk/tools/modtool.py 2007-07-28 00:33:39 UTC (rev 140) @@ -31,6 +31,13 @@ sys.exit(0) def main(): + guiVersion = (os.path.basename(sys.executable).lower() == "pythonw.exe") + if guiVersion: + log().info("using GUI version") + import wx + MainApp = wx.PySimpleApp(0) + wx.InitAllImageHandlers() #you may or may not need this + # check for valid RoR Directory! import ror.settingsManager rorpath = ror.settingsManager.getSettingsManager().getSetting("RigsOfRods", "BasePath") @@ -80,7 +87,14 @@ else: installtarget = None import ror.modtool - ror.modtool.ModTool().work(mode, targetfile, verbose, dryrun, installtarget) + result = ror.modtool.ModTool().work(mode, targetfile, verbose, dryrun, installtarget) + if guiVersion: + msg = "Installation failed! :( Please have a look at the file editorlog.log" + if result: + msg = "Installation successfull! You can now use the Mod." + dlg = wx.MessageDialog(None, msg, "Info", wx.OK | wx.ICON_INFORMATION) + dlg.ShowModal() + dlg.Destroy() if __name__=="__main__": main() Modified: trunk/tools/update.py =================================================================== --- trunk/tools/update.py 2007-07-27 19:19:31 UTC (rev 139) +++ trunk/tools/update.py 2007-07-28 00:33:39 UTC (rev 140) @@ -2,7 +2,7 @@ def main(): sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "lib")) - guiVersion = True + guiVersion = (os.path.basename(sys.executable).lower() == "pythonw.exe") if guiVersion: import wx Copied: trunk/truckeditor.py (from rev 135, trunk/truckeditor.pyw) =================================================================== --- trunk/truckeditor.py (rev 0) +++ trunk/truckeditor.py 2007-07-28 00:33:39 UTC (rev 140) @@ -0,0 +1,28 @@ +#Thomas Fischer 31/05/2007, th...@th... +import sys, os, os.path + +def main(): + """ + main method + """ + + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) + import ror.settingsManager + path = ror.settingsManager.getSettingsManager().getSetting("RigsOfRods", "BasePath") + if not os.path.isfile(os.path.join(path,"RoR.exe")): + import ror.starter + ror.starter.startApp() + + # Import Psyco if available + try: + import psyco + psyco.full() + except ImportError: + pass + + import rortruckeditor.MainFrame + rortruckeditor.MainFrame.startApp() + + +if __name__=="__main__": + main() \ No newline at end of file Deleted: trunk/truckeditor.pyw =================================================================== --- trunk/truckeditor.pyw 2007-07-27 19:19:31 UTC (rev 139) +++ trunk/truckeditor.pyw 2007-07-28 00:33:39 UTC (rev 140) @@ -1,28 +0,0 @@ -#Thomas Fischer 31/05/2007, th...@th... -import sys, os, os.path - -def main(): - """ - main method - """ - - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) - import ror.settingsManager - path = ror.settingsManager.getSettingsManager().getSetting("RigsOfRods", "BasePath") - if not os.path.isfile(os.path.join(path,"RoR.exe")): - import ror.starter - ror.starter.startApp() - - # Import Psyco if available - try: - import psyco - psyco.full() - except ImportError: - pass - - import rortruckeditor.MainFrame - rortruckeditor.MainFrame.startApp() - - -if __name__=="__main__": - main() \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-07-28 10:15:57
|
Revision: 142 http://roreditor.svn.sourceforge.net/roreditor/?rev=142&view=rev Author: rorthomas Date: 2007-07-28 03:15:55 -0700 (Sat, 28 Jul 2007) Log Message: ----------- * small fixes at some sharp corners Modified Paths: -------------- trunk/devtools/setup/setup.nsi trunk/lib/ror/bugreport.py trunk/lib/ror/svn.py trunk/lib/ror/terrainparser.py trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py trunk/tools/modtool.py Modified: trunk/devtools/setup/setup.nsi =================================================================== --- trunk/devtools/setup/setup.nsi 2007-07-28 09:17:08 UTC (rev 141) +++ trunk/devtools/setup/setup.nsi 2007-07-28 10:15:55 UTC (rev 142) @@ -2,7 +2,7 @@ ; HM NIS Edit Wizard helper defines !define PRODUCT_NAME "RoRToolkit" -!define PRODUCT_VERSION "0.1.139" +!define PRODUCT_VERSION "0.1.140" !define PRODUCT_PUBLISHER "Thomas Fischer" !define PRODUCT_WEB_SITE "http://wiki.rigsofrods.com/index.php?title=RoRToolkit" !define PRODUCT_UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" @@ -17,7 +17,7 @@ BrandingText "Rigs of Rods Toolkit" InstProgressFlags smooth colored XPStyle on -ShowInstDetails show +#ShowInstDetails show ShowUninstDetails show SetDateSave on #SetDatablockOptimize on @@ -196,7 +196,8 @@ WriteRegStr HKCR "RoRRepo" "URL Protocol" "" WriteRegStr HKCR "RoRRepo\shell" "" "" WriteRegStr HKCR "RoRRepo\shell\open" "" "" - WriteRegStr HKCR 'RoRRepo\shell\open\command' '' '"%systemdrive%\python25\pythonw.exe" "$INSTDIR\tools\modgui.py installrepo" "%1"' + ReadEnvStr $0 SYSTEMDRIVE + WriteRegStr HKCR 'RoRRepo\shell\open\command' '' '"$0\python25\python.exe" "$INSTDIR\tools\modtool.py" "installrepo" "%1"' Banner::destroy FunctionEnd @@ -231,31 +232,33 @@ SectionIn 1 2 RO SetOutPath "$INSTDIR" SetOverwrite try - File /r /x *.pyc /x doc /x devtools /x 3rdparty /x downloaded /x graphs ..\..\* + File /r /x *.pyc /x *.pyo /x doc /x devtools /x 3rdparty /x downloaded /x graphs ..\..\* SectionEnd !insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN -!insertmacro MUI_DESCRIPTION_TEXT ${SEC01} "installs python 2.5" -!insertmacro MUI_DESCRIPTION_TEXT ${SEC02} "installs required Tools (directX)" -!insertmacro MUI_DESCRIPTION_TEXT ${SEC03} "installs optional Tools (PyWin32 for bugreporting, PyParsing and GraphViz for Dependency Graphs)" -!insertmacro MUI_DESCRIPTION_TEXT ${SEC04} "installs the RoR Toolkit. It includes the Truckeditor, Terraineditor and various tools" +!insertmacro MUI_DESCRIPTION_TEXT ${SEC01} "python 2.5" +!insertmacro MUI_DESCRIPTION_TEXT ${SEC02} "required Tools (directX)" +!insertmacro MUI_DESCRIPTION_TEXT ${SEC03} "optional Tools (PyWin32 for bugreporting, PyParsing and GraphViz for Dependency Graphs)" +!insertmacro MUI_DESCRIPTION_TEXT ${SEC04} "the RoR Toolkit. It includes the Truckeditor, Terraineditor and various other tools" !insertmacro MUI_FUNCTION_DESCRIPTION_END Function "LaunchPostInstallation" - ExecWait "$INSTDIR\tools\update.py" - ExecWait "%systemdrive%\python25\pythonw.exe $INSTDIR\rortoolkit.py" + ReadEnvStr $0 SYSTEMDRIVE + ExecWait "$0\python25\python.exe $INSTDIR\tools\update.py" + ExecWait "$0\python25\python.exe $INSTDIR\rortoolkit.py" FunctionEnd Section -AdditionalIcons + ReadEnvStr $0 SYSTEMDRIVE SetOutPath $INSTDIR WriteIniStr "$INSTDIR\${PRODUCT_NAME}.url" "InternetShortcut" "URL" "${PRODUCT_WEB_SITE}" CreateDirectory "$SMPROGRAMS\RoRToolkit" CreateShortCut "$SMPROGRAMS\RoRToolkit\Website.lnk" "$INSTDIR\${PRODUCT_NAME}.url" CreateShortCut "$SMPROGRAMS\RoRToolkit\Uninstall.lnk" "$INSTDIR\uninst.exe" - CreateShortCut '$SMPROGRAMS\RoRToolkit\RoR Terrain Editor.lnk' '"%systemdrive%\python25\pythonw.exe" "$INSTDIR\terraineditor.py"' '' '$INSTDIR\ror.ico' - CreateShortCut '$SMPROGRAMS\RoRToolkit\RoR Truck Editor.lnk' '"%systemdrive%\python25\pythonw.exe" "$INSTDIR\truckeditor.py"' '' '$INSTDIR\ror.ico' - CreateShortCut '$SMPROGRAMS\RoRToolkit\RoR Toolkit.lnk' '"%systemdrive%\python25\pythonw.exe" "$INSTDIR\rortoolkit.py"' '' '$INSTDIR\ror.ico' + CreateShortCut '$SMPROGRAMS\RoRToolkit\RoR Terrain Editor.lnk' '"$0\python25\python.exe" "$INSTDIR\terraineditor.py"' '' '$INSTDIR\ror.ico' + CreateShortCut '$SMPROGRAMS\RoRToolkit\RoR Truck Editor.lnk' '"$0\python25\python.exe" "$INSTDIR\truckeditor.py"' '' '$INSTDIR\ror.ico' + CreateShortCut '$SMPROGRAMS\RoRToolkit\RoR Toolkit.lnk' '"$0\python25\python.exe" "$INSTDIR\rortoolkit.py"' '' '$INSTDIR\ror.ico' SectionEnd Section -Post Modified: trunk/lib/ror/bugreport.py =================================================================== --- trunk/lib/ror/bugreport.py 2007-07-28 09:17:08 UTC (rev 141) +++ trunk/lib/ror/bugreport.py 2007-07-28 10:15:55 UTC (rev 142) @@ -77,7 +77,7 @@ try: import sysinfo except: - dlg = wx.MessageDialog(self, "You must install pywin32 first.\nYou can find the setup in INSTALLDIR/tools/pywin32-setup.exe\nPLease note that you must restart this program after the pywin installation.", "Error", wx.OK | wx.ICON_INFORMATION) + dlg = wx.MessageDialog(self, "You must install pywin32 first.\nYou can find the setup in INSTALLDIR\tools\3rdparty\pywin32-setup.exe (This means you must install it by hand!)\nPlease note that you must restart this program after the pywin installation.", "Error", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() self.Close() Modified: trunk/lib/ror/svn.py =================================================================== --- trunk/lib/ror/svn.py 2007-07-28 09:17:08 UTC (rev 141) +++ trunk/lib/ror/svn.py 2007-07-28 10:15:55 UTC (rev 142) @@ -97,8 +97,8 @@ try: client.unlock(path) except Exception, err: - log().error("Error while svn unlock:") - log().error(str(err)) + #log().error("Error while svn unlock:") + #log().error(str(err)) pass revision_before = getRevision(client, path) Modified: trunk/lib/ror/terrainparser.py =================================================================== --- trunk/lib/ror/terrainparser.py 2007-07-28 09:17:08 UTC (rev 141) +++ trunk/lib/ror/terrainparser.py 2007-07-28 10:15:55 UTC (rev 142) @@ -232,16 +232,25 @@ lines.append(self.SkyColorLine.strip()+"\n") ar = [] - ar.append(str(self.TruckStartPosition[0])) - ar.append(str(self.TruckStartPosition[1])) - ar.append(str(self.TruckStartPosition[2])) - ar.append(str(self.CameraStartPosition[0])) - ar.append(str(self.CameraStartPosition[1])) - ar.append(str(self.CameraStartPosition[2])) + try: + ar.append(str(self.TruckStartPosition[0])) + ar.append(str(self.TruckStartPosition[1])) + ar.append(str(self.TruckStartPosition[2])) + except Exception, err: + log().error(str(err)) + try: + ar.append(str(self.CameraStartPosition[0])) + ar.append(str(self.CameraStartPosition[1])) + ar.append(str(self.CameraStartPosition[2])) + except Exception, err: + log().error(str(err)) if not self.CharacterStartPosition is None: - ar.append(str(self.CharacterStartPosition[0])) - ar.append(str(self.CharacterStartPosition[1])) - ar.append(str(self.CharacterStartPosition[2])) + try: + ar.append(str(self.CharacterStartPosition[0])) + ar.append(str(self.CharacterStartPosition[1])) + ar.append(str(self.CharacterStartPosition[2])) + except Exception, err: + log().error(str(err)) startline = ", ".join(ar)+"\n" lines.append(startline) Modified: trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py =================================================================== --- trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py 2007-07-28 09:17:08 UTC (rev 141) +++ trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py 2007-07-28 10:15:55 UTC (rev 142) @@ -384,19 +384,35 @@ self.createWaterPlane() self.createArrows() - if not self.terrain.CharacterStartPosition is None: - self.camera.setPosition(self.terrain.CharacterStartPosition) - else: - self.camera.setPosition(self.terrain.CameraStartPosition) + try: + if not self.terrain.CharacterStartPosition is None: + self.camera.setPosition(self.terrain.CharacterStartPosition) + else: + self.camera.setPosition(self.terrain.CameraStartPosition) + except Exception, err: + log().error("Error while setting initial camera:") + log().error(str(err)) for truck in self.terrain.trucks: - self.addTruckToTerrain(data=truck) + try: + self.addTruckToTerrain(data=truck) + except Exception, err: + log().error("Error while adding a truck to the terrain:") + log().error(str(err)) for load in self.terrain.loads: - self.addTruckToTerrain(data=load) + try: + self.addTruckToTerrain(data=load) + except Exception, err: + log().error("Error while adding a load to the terrain:") + log().error(str(err)) for object in self.terrain.objects: - self.addObjectToTerrain(data=object) + try: + self.addObjectToTerrain(data=object) + except Exception, err: + log().error("Error while adding an object to the terrain:") + log().error(str(err)) self.currentStatusMsg = "Terrain loaded" Modified: trunk/tools/modtool.py =================================================================== --- trunk/tools/modtool.py 2007-07-28 09:17:08 UTC (rev 141) +++ trunk/tools/modtool.py 2007-07-28 10:15:55 UTC (rev 142) @@ -3,6 +3,9 @@ sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "lib")) +from ror.logger import log +from ror.settingsManager import getSettingsManager + def usage(): print "usage (general): %s <mode> <additionaloptions> [--verbose] [--dryrun]" % (os.path.basename(sys.argv[0])) print "list <filename>" @@ -31,7 +34,7 @@ sys.exit(0) def main(): - guiVersion = (os.path.basename(sys.executable).lower() == "pythonw.exe") + guiVersion = True #(os.path.basename(sys.executable).lower() == "pythonw.exe") if guiVersion: log().info("using GUI version") import wx @@ -91,7 +94,7 @@ if guiVersion: msg = "Installation failed! :( Please have a look at the file editorlog.log" if result: - msg = "Installation successfull! You can now use the Mod." + msg = "Installation successfull! You can now use the Mod.\n more details can be found in the log window!\n(The Log Window will close when you click OK)" dlg = wx.MessageDialog(None, msg, "Info", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-08-01 12:09:59
|
Revision: 148 http://roreditor.svn.sourceforge.net/roreditor/?rev=148&view=rev Author: rorthomas Date: 2007-08-01 05:09:55 -0700 (Wed, 01 Aug 2007) Log Message: ----------- * made water material more transparent * new GUI system, not completed yet, WIP! Modified Paths: -------------- trunk/lib/rorterraineditor/MainFrame.py trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py trunk/media/materials/mysimple.material Added Paths: ----------- trunk/lib/rorterraineditor/MainFrame_Tools.py Modified: trunk/lib/rorterraineditor/MainFrame.py =================================================================== --- trunk/lib/rorterraineditor/MainFrame.py 2007-07-29 16:07:10 UTC (rev 147) +++ trunk/lib/rorterraineditor/MainFrame.py 2007-08-01 12:09:55 UTC (rev 148) @@ -1,4 +1,5 @@ -#Thomas Fischer 31/05/2007, th...@th... +import sys, os, os.path + from wxogre.OgreManager import * from ror.RoROgreWindow import * @@ -10,209 +11,254 @@ from RoRTerrainSelectedObjectOgreWindow import * from RoRTerrainSelectedObjectTopOgreWindow import * -ID_ABOUT = 101 -ID_OPENFILE = 102 -ID_SAVEFILE = 103 -ID_VIEWOBJ = 104 -ID_OGRESET = 105 -ID_SHOWHELP = 106 -ID_ADDTRUCK = 107 -ID_ADDMESH = 108 -ID_CHECKUPDATE = 109 -ID_SAVEFILEAS = 110 -ID_TERRAINCOLLISION = 111 -ID_EXIT = 199 +from MainFrame_Tools import * + +import wx +import wx.grid +import wx.html +import wx.aui +import cStringIO + +ID_OpenTerrain = wx.NewId() +ID_SaveTerrain = wx.NewId() +ID_SaveTerrainAs = wx.NewId() +ID_AddObject = wx.NewId() +ID_DeleteSelection = wx.NewId() +ID_CopySelection = wx.NewId() +ID_PasteSelection = wx.NewId() +ID_UndoAction = wx.NewId() +ID_RedoAction = wx.NewId() +ID_FindObject = wx.NewId() +ID_Quit = wx.NewId() + +ID_CreateOgre = wx.NewId() + +ID_CreateTree = wx.NewId() +ID_CreateGrid = wx.NewId() +ID_CreateText = wx.NewId() +ID_CreateHTML = wx.NewId() +ID_CreateSizeReport = wx.NewId() +ID_GridContent = wx.NewId() +ID_TextContent = wx.NewId() +ID_TreeContent = wx.NewId() +ID_HTMLContent = wx.NewId() +ID_SizeReportContent = wx.NewId() +ID_CreatePerspective = wx.NewId() +ID_CopyPerspective = wx.NewId() + +ID_Settings = wx.NewId() +ID_About = wx.NewId() +ID_FirstPerspective = ID_CreatePerspective+1000 + DATADIR = "data" TRUCKDIR = os.path.join(DATADIR, "trucks") TERRAINDIR = os.path.join(DATADIR, "terrains") OBJECTDIR = os.path.join(DATADIR, "objects") - -class MainFrame(wx.Frame): - def __init__(self, *args, **kwds): - kwds["style"] = wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION | wx.CLIP_CHILDREN +class MainFrame(wx.Frame): + + def __init__(self, parent, id=-1, title="", pos=wx.DefaultPosition, + size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE | + wx.SUNKEN_BORDER | + wx.CLIP_CHILDREN): + + wx.Frame.__init__(self, parent, id, title, pos, size, style) - wx.Frame.__init__(self, *args, **kwds) + # tell FrameManager to manage this frame + self._mgr = wx.aui.AuiManager() + self._mgr.SetManagedWindow(self) + + self._perspectives = [] + self.n = 0 + self.x = 0 + + self.SetIcon(wx.Icon('ror.ico',wx.BITMAP_TYPE_ICO)) + # create menu + mb = wx.MenuBar() - #main splitter - self.splitter = wx.SplitterWindow(self, wx.ID_ANY, style=wx.SP_PERMIT_UNSPLIT|wx.SP_3DSASH) - self.splitterleft = wx.Panel(self.splitter, wx.ID_ANY) - self.splitterright = wx.Panel(self.splitter, wx.ID_ANY) - self.splitter.SetSashGravity(1) - self.splitter.SetSashPosition(100) - self.splitter.SetMinimumPaneSize(200) + file_menu = wx.Menu() + file_menu.Append(ID_OpenTerrain, "Open Terrain") + file_menu.Append(wx.ID_EXIT, "Exit") - #viewsplitter - self.viewsplitter = wx.SplitterWindow(self.splitterright, wx.ID_ANY) - self.viewsplitterup = wx.Panel(self.viewsplitter, wx.ID_ANY) - self.viewsplitterdown = wx.Panel(self.viewsplitter, wx.ID_ANY) - self.splitter.SetSashGravity(0.5) - self.splitter.SetSashPosition(100) - self.splitter.SetMinimumPaneSize(200) + view_menu = wx.Menu() + view_menu.Append(ID_CreateOgre, "Create OgreWindow") + view_menu.Append(ID_CreateText, "Create Text Control") + view_menu.Append(ID_CreateHTML, "Create HTML Control") + view_menu.Append(ID_CreateTree, "Create Tree") + view_menu.Append(ID_CreateGrid, "Create Grid") + view_menu.Append(ID_CreateSizeReport, "Create Size Reporter") + view_menu.AppendSeparator() + view_menu.Append(ID_GridContent, "Use a Grid for the Content Pane") + view_menu.Append(ID_TextContent, "Use a Text Control for the Content Pane") + view_menu.Append(ID_HTMLContent, "Use an HTML Control for the Content Pane") + view_menu.Append(ID_TreeContent, "Use a Tree Control for the Content Pane") + view_menu.Append(ID_SizeReportContent, "Use a Size Reporter for the Content Pane") + - self.rordir = getSettingsManager().getSetting("RigsOfRods", "BasePath") + self.managerInit() + options_menu = wx.Menu() + options_menu.Append(ID_Settings, "GUI Settings Pane") - #ogre windows - self.terrainOgreWin = RoRTerrainOgreWindow(self.splitterleft, wx.ID_ANY, rordir=self.rordir) - self.sharedOgreWin = RoRTerrainSelectedObjectOgreWindow(self.viewsplitterup, wx.ID_ANY, self.terrainOgreWin) - self.sharedOgreWin2 = RoRTerrainSelectedObjectTopOgreWindow(self.viewsplitterdown, wx.ID_ANY, self.terrainOgreWin) + self._perspectives_menu = wx.Menu() + self._perspectives_menu.Append(ID_CreatePerspective, "Create Perspective") + self._perspectives_menu.Append(ID_CopyPerspective, "Copy Perspective Data To Clipboard") + self._perspectives_menu.AppendSeparator() + self._perspectives_menu.Append(ID_FirstPerspective+0, "Default Startup") + self._perspectives_menu.Append(ID_FirstPerspective+1, "All Panes") + + help_menu = wx.Menu() + help_menu.Append(ID_About, "About...") - #some labels - #self.helptext = wx.StaticText(self.splitterleft, wx.ID_ANY, "short help: right click = rotate; ctrl + right click, AWSD, mouse wheel = move") - #self.rotatingLabel = wx.StaticText(self.viewsplitterup, wx.ID_ANY, "rotating") - #self.topLabel = wx.StaticText(self.viewsplitterdown, wx.ID_ANY, "top") + mb.Append(file_menu, "File") + mb.Append(view_menu, "View") + mb.Append(self._perspectives_menu, "Perspectives") + mb.Append(options_menu, "Options") + mb.Append(help_menu, "Help") + + self.SetMenuBar(mb) - #Timer creation (for label updates) - self.timer = wx.Timer() - self.timer.SetOwner(self) #Sets the timer to notify self: binding the timer event is not enough - self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) - self.timer.Start(200) + self.statusbar = self.CreateStatusBar(5, 0, wx.ID_ANY, "mainstatusbar") + self.statusbar.SetStatusWidths([-1, 200, 130, 250, 80]) + # min size for the frame itself isn't completely done. + # see the end up FrameManager::Update() for the test + # code. For now, just hard code a frame minimum size + self.SetMinSize(wx.Size(600, 400)) + try: + import ror.svn + self.SetTitle("Rigs of Rods Terrain Editor revision %d" % ror.svn.getRevision()) + except: + self.SetTitle("Rigs of Rods Terrain Editor") + + # create some toolbars + tb1 = wx.ToolBar(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER) + tb1.SetToolBitmapSize(wx.Size(16,16)) + tb1.AddLabelTool(ID_OpenTerrain, "Open Terrain", wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN)) + tb1.AddLabelTool(ID_SaveTerrain, "Save Terrain", wx.ArtProvider_GetBitmap(wx.ART_FILE_SAVE)) + tb1.AddLabelTool(ID_SaveTerrainAs, "Save Terrain as", wx.ArtProvider_GetBitmap(wx.ART_FILE_SAVE_AS)) + tb1.AddSeparator() + tb1.AddLabelTool(ID_AddObject, "Add Something", wx.ArtProvider_GetBitmap(wx.ART_NEW)) + tb1.AddLabelTool(ID_DeleteSelection, "Delete Selection", wx.ArtProvider_GetBitmap(wx.ART_DELETE)) + tb1.AddSeparator() + tb1.AddLabelTool(ID_CopySelection, "Copy Selection", wx.ArtProvider_GetBitmap(wx.ART_COPY)) + tb1.AddLabelTool(ID_PasteSelection, "Paste Selection", wx.ArtProvider_GetBitmap(wx.ART_PASTE)) + tb1.AddSeparator() + tb1.AddLabelTool(ID_UndoAction, "Undo last Action", wx.ArtProvider_GetBitmap(wx.ART_UNDO)) + tb1.AddLabelTool(ID_RedoAction, "Redo last Undo", wx.ArtProvider_GetBitmap(wx.ART_REDO)) + tb1.AddSeparator() + tb1.AddLabelTool(ID_FindObject, "Find Object", wx.ArtProvider_GetBitmap(wx.ART_FIND)) + tb1.AddSeparator() + tb1.AddLabelTool(ID_Quit, "Quit", wx.ArtProvider_GetBitmap(wx.ART_QUIT)) + tb1.EnableTool(ID_SaveTerrain, False) + tb1.EnableTool(ID_SaveTerrainAs, False) + tb1.Realize() + self.tb1 = tb1 + + # add a bunch of panes + self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo(). + Name("test1").Caption("Pane Caption").Top(). + CloseButton(True).MaximizeButton(True)) + + self._mgr.AddPane(SettingsPanel(self, self), wx.aui.AuiPaneInfo(). + Name("settings").Caption("Dock Manager Settings"). + Dockable(False).Float().Hide().CloseButton(True).MaximizeButton(True)) + + # create some center panes + self._mgr.AddPane(self.CreateTreeCtrl(), wx.aui.AuiPaneInfo().Name("tree_content"). + CenterPane().Hide()) + + self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo().Name("sizereport_content"). + CenterPane().Hide()) + + self._mgr.AddPane(self.CreateTextCtrl(), wx.aui.AuiPaneInfo().Name("text_content"). + CenterPane().Hide()) + + self._mgr.AddPane(self.CreateHTMLCtrl(), wx.aui.AuiPaneInfo().Name("grid_content"). + CenterPane().Hide()) + #Timer creation (for rendering) self.ogreTimer = wx.Timer() self.ogreTimer.SetOwner(self) self.Bind(wx.EVT_TIMER, self.onUpdateRender, self.ogreTimer) self.ogreTimer.Start(25) - #create statusbar - self.statusbar = self.CreateStatusBar(5, 0, wx.ID_ANY, "mainstatusbar") - self.statusbar.SetStatusWidths([-1, 200, 130, 250, 80]) - #self.statusbar.SetStatusText("", 1) + # create timer for gui update + self.guitimer = wx.Timer() + self.guitimer.SetOwner(self) #Sets the timer to notify self: binding the timer event is not enough + self.Bind(wx.EVT_TIMER, self.OnGUITimer, self.guitimer) + self.guitimer.Start(200) - #create toolbar - #self.toolbar = wx.ToolBar(self, wx.ID_ANY, style = wx.TB_HORZ_TEXT) - #self.SetToolBar(self.toolbar ) - #bitmap = wx.Bitmap("media/gui/OpenFile.gif", wx.BITMAP_TYPE_GIF) - #self.toolbar.DoAddTool(0, "Open Terrain", bitmap, bitmap, wx.ITEM_NORMAL, "Open Terrain", "Opens a new terrain for edit") - #create general settings - #self.GeneralSettingsPanel = wx.Panel(self, wx.ID_ANY) - self.terrainName = wx.StaticText(self, wx.ID_ANY, "Terrain Name:") - self.terrainNamectrl = wx.TextCtrl(self, wx.ID_ANY) - self.Bind(wx.EVT_TEXT, self.OnChangeTerrainNameChange, self.terrainNamectrl) + self.rordir = getSettingsManager().getSetting("RigsOfRods", "BasePath") + self.terrainOgreWin = RoRTerrainOgreWindow(self, wx.ID_ANY, rordir=self.rordir) + self._mgr.AddPane(self.terrainOgreWin, wx.aui.AuiPaneInfo().Name("ogre_content"). + CenterPane()) + + # add the toolbars to the manager + + self._mgr.AddPane(tb1, wx.aui.AuiPaneInfo(). + Name("tb1"). + Caption("General Toolbar"). + ToolbarPane().Top(). + LeftDockable(False). + RightDockable(False) + ) - self.waterLevelText = wx.StaticText(self, wx.ID_ANY, "Water Level: 0") - self.waterlevelctrl = wx.Slider(self, wx.ID_ANY) - self.waterlevelctrl.max = 300 - self.Bind(wx.EVT_SCROLL, self.OnChangeWaterLevel, self.waterlevelctrl) + # make some default perspectives + perspective_all = self._mgr.SavePerspective() + + # all - perspective + all_panes = self._mgr.GetAllPanes() + for ii in xrange(len(all_panes)): + if not all_panes[ii].IsToolbar(): + all_panes[ii].Hide() + self._mgr.GetPane("ogre_content").Show() + perspective_default = self._mgr.SavePerspective() - #self.CurrEntName = wx.StaticText(self, wx.ID_ANY, "\n\n\n") - #self.PosText = wx.StaticText(self, wx.ID_ANY, "Position: x,y,z") - #self.terrPosX = wx.TextCtrl(self, wx.ID_ANY) - #self.terrPosY = wx.TextCtrl(self, wx.ID_ANY) - #self.terrPosZ = wx.TextCtrl(self, wx.ID_ANY) - #self.RotText = wx.StaticText(self, wx.ID_ANY, "Rotation: x,y,z") - #self.terrRotX = wx.TextCtrl(self, wx.ID_ANY) - #self.terrRotY = wx.TextCtrl(self, wx.ID_ANY) - #self.terrRotZ = wx.TextCtrl(self, wx.ID_ANY) - #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrPosX) - #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrPosY) - #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrPosZ) - #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrRotX) - #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrRotY) - #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrRotZ) + self._perspectives.append(perspective_default) + self._perspectives.append(perspective_all) - self.btnResetRotation = wx.Button(self, wx.ID_ANY, "Reset Rotation") - self.Bind(wx.EVT_BUTTON, self.OnBtnResetRotation, self.btnResetRotation) - self.btnStickToGround = wx.ToggleButton(self, wx.ID_ANY, "Stick to Ground") - self.Bind(wx.EVT_TOGGLEBUTTON, self.OnBtnStickToGroundChange, self.btnStickToGround) - - - #menu creation - menuBar = wx.MenuBar() - file_menu = wx.Menu() - self.fileopenmenu = file_menu.Append(ID_OPENFILE, "&Open", "Open Terrain") - self.filesavemenu = file_menu.Append(ID_SAVEFILE, "&Save", "Save Terrain") - self.filesaveasmenu = file_menu.Append(ID_SAVEFILEAS, "&Save as", "Save Terrain as") - - self.filesavemenu.Enable(False) - self.filesaveasmenu.Enable(False) - file_menu.AppendSeparator() - file_menu.Append(ID_EXIT, "E&xit", "Terminate the program") - menuBar.Append(file_menu, "&File"); - - view_menu = wx.Menu() - self.mnuterraincollision = view_menu.AppendCheckItem(ID_TERRAINCOLLISION, "Camera collides with Terrain", "") - self.mnuterraincollision.Check(True) - view_menu.AppendSeparator() - self.viewObjectDetails = view_menu.AppendCheckItem(ID_VIEWOBJ, "&Additional Object View Window", "creates two additional views") - self.viewObjectDetails.Check(False) - view_menu.AppendSeparator() - view_menu.Append(ID_OGRESET, "&Ogre Settings", "Change Ogre Display Settings") - menuBar.Append(view_menu, "&View"); - - add_menu = wx.Menu() - add_menu.Append(ID_ADDTRUCK, "&Truck/Load", "add a Truck or a Load to the terrain") - self.Bind(wx.EVT_MENU, self.OnAddTruck, id=ID_ADDTRUCK) - add_menu.Append(ID_ADDMESH, "&Object", "add a static Object to the terrain") - self.Bind(wx.EVT_MENU, self.OnAddMesh, id=ID_ADDMESH) - menuBar.Append(add_menu, "&Add"); - help_menu = wx.Menu() - help_menu.Append(ID_SHOWHELP, "Show &Help", "view the documentation") - help_menu.AppendSeparator() - help_menu.Append(ID_ABOUT, "&About", "More information about this program") - menuBar.Append(help_menu, "&Help"); - - #bindings - self.SetMenuBar(menuBar) - self.__set_properties() - self.__do_layout() - self.Bind(wx.EVT_MENU, self.OnExit, id=ID_EXIT) - self.Bind(wx.EVT_MENU, self.OnFileOpen, id=ID_OPENFILE) - self.Bind(wx.EVT_MENU, self.OnFileSave, id=ID_SAVEFILE) - self.Bind(wx.EVT_MENU, self.OnFileSaveAs, id=ID_SAVEFILEAS) - self.Bind(wx.EVT_MENU, self.OnAbout, id=ID_ABOUT) - self.Bind(wx.EVT_MENU, self.onViewObjectDetails, id=ID_VIEWOBJ) - self.Bind(wx.EVT_MENU, self.OnChangeOgreSettings, id=ID_OGRESET) - self.Bind(wx.EVT_MENU, self.OnCameraTerrainCollision, id=ID_TERRAINCOLLISION) + # "commit" all changes made to FrameManager + self._mgr.Update() - def OnAbout(self, event=None): - ShowOnAbout() + self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) + self.Bind(wx.EVT_SIZE, self.OnSize) + self.Bind(wx.EVT_CLOSE, self.OnClose) + + # Show How To Use The Closing Panes Event + self.Bind(wx.aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose) + - def OnCheckUpdate(self, event=None): - pass + self.Bind(wx.EVT_MENU, self.OnOpenTerrain, id=ID_OpenTerrain) + self.Bind(wx.EVT_MENU, self.OnSaveTerrain, id=ID_SaveTerrain) + self.Bind(wx.EVT_MENU, self.OnSaveTerrainAs, id=ID_SaveTerrainAs) - def OnCameraTerrainCollision(self, event=None): - self.terrainOgreWin.CameraLandCollision(self.mnuterraincollision.IsChecked()) + self.Bind(wx.EVT_MENU, self.OnCreateOgre, id=ID_CreateOgre) - def OnHelp(self, event=None): - import HelpFrame - HelpFrame.showHelpFrame() - - def OnAddTruck(self, event=None): - default = "" - if self.rordir: - default = os.path.join(self.rordir, TRUCKDIR) - dialog = wx.FileDialog(self, "Add Truck", default, "", "Truck and Load Files (*.truck,*.load)|*.truck;*.load", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) - res = dialog.ShowModal() - if res == wx.ID_OK: - if not self.terrainOgreWin.addTruckToTerrain(truckFilename=dialog.GetPath()): - dlg = wx.MessageDialog(self, "You must select a position on the ground first!", "error", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() + self.Bind(wx.EVT_MENU, self.OnCreateTree, id=ID_CreateTree) + self.Bind(wx.EVT_MENU, self.OnCreateGrid, id=ID_CreateGrid) + self.Bind(wx.EVT_MENU, self.OnCreateText, id=ID_CreateText) + self.Bind(wx.EVT_MENU, self.OnCreateHTML, id=ID_CreateHTML) + self.Bind(wx.EVT_MENU, self.OnCreateSizeReport, id=ID_CreateSizeReport) + self.Bind(wx.EVT_MENU, self.OnCreatePerspective, id=ID_CreatePerspective) + self.Bind(wx.EVT_MENU, self.OnCopyPerspective, id=ID_CopyPerspective) - def OnAddMesh(self, event=None): - default = "" - if self.rordir: - default = os.path.join(self.rordir, OBJECTDIR) - dialog = wx.FileDialog(self, "Add Object", default, "", "RoR Object Definitions (*.odef)|*.odef", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) - res = dialog.ShowModal() - if res == wx.ID_OK: - if not self.terrainOgreWin.addObjectToTerrain(odefFilename=dialog.GetPath()): - dlg = wx.MessageDialog(self, "You must select a position on the ground first!", "error", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - - - def OnBtnResetRotation(self, event=None): - self.terrainOgreWin.ObjectResetRotation() - - def OnBtnStickToGroundChange(self, event=None): - self.terrainOgreWin.stickCurrentObjectToGround = self.btnStickToGround.GetValue() + self.Bind(wx.EVT_MENU, self.OnSettings, id=ID_Settings) + self.Bind(wx.EVT_MENU, self.OnChangeContentPane, id=ID_GridContent) + self.Bind(wx.EVT_MENU, self.OnChangeContentPane, id=ID_TreeContent) + self.Bind(wx.EVT_MENU, self.OnChangeContentPane, id=ID_TextContent) + self.Bind(wx.EVT_MENU, self.OnChangeContentPane, id=ID_SizeReportContent) + self.Bind(wx.EVT_MENU, self.OnChangeContentPane, id=ID_HTMLContent) + self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT) + self.Bind(wx.EVT_MENU, self.OnAbout, id=ID_About) + + self.Bind(wx.EVT_MENU_RANGE, self.OnRestorePerspective, id=ID_FirstPerspective, + id2=ID_FirstPerspective+1000) + def updateObjPosRot(self, event=None): self.statusbar.SetStatusText(self.terrainOgreWin.currentStatusMsg, 1) if self.terrainOgreWin.terrain is None: @@ -232,40 +278,36 @@ txt = "%0.2f, %0.2f, %0.2f / %0.2f, %0.2f, %0.2f" % (posx, posy, posz, rotx, roty, rotz) self.statusbar.SetStatusText(txt, 3) - #pos = n.getPosition() - #self.terrPosX.SetValue(str(round(pos.x,2))) - #self.terrPosY.SetValue(str(round(pos.y,2))) - #self.terrPosZ.SetValue(str(round(pos.z,2))) - #rot = n.getOrientation() - #self.terrRotX.SetValue(str(round(ogre.Radian(rot.getPitch(False)+90).valueDegrees(),2))) - #self.terrRotY.SetValue(str(round(ogre.Radian(rot.getYaw(False)).valueDegrees(),2))) - #self.terrRotZ.SetValue(str(round(ogre.Radian(rot.getRoll(False)).valueDegrees(),2))) + def OnGUITimer(self, event): + #fill labels with some information, all windows have the same FPS! + txt = "%0.2f FPS" % (self.terrainOgreWin.renderWindow.getStatistics().lastFPS) + self.statusbar.SetStatusText(txt, 4) + self.updateObjPosRot() - #def OnChangeObjPosRot(self, event=None): - # pass - - def OnChangeTerrainNameChange(self, event=None): - self.terrainOgreWin.terrain.TerrainName = self.terrainNamectrl.GetValue() - - def OnChangeWaterLevel(self, event=None): - if not self.terrainOgreWin.terrain is None: - self.terrainOgreWin.terrain.WaterHeight = self.waterlevelctrl.GetValue() - self.waterLevelText.Label = "Water Level: %0.1f" % (self.terrainOgreWin.terrain.WaterHeight) - self.terrainOgreWin.updateWaterPlane() - - def OnChangeOgreSettings(self, event): - getOgreManager().getRoot().showConfigDialog() - dlg = wx.MessageDialog(self, "You must restart the program for the settings to get active", "Ogre Settings", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - - def OnFileSave(self, event): + def onUpdateRender(self, event=None): + getOgreManager().RenderAll() + pass + + def OnOpenTerrain(self, event=None): + default = "" + if self.rordir: + default = os.path.join(self.rordir, TERRAINDIR) + dialog = wx.FileDialog(self, "Open Terrain", default, "", "Terrain Files (*.terrn)|*.terrn", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) + res = dialog.ShowModal() + if res == wx.ID_OK: + filename = dialog.GetPath() + self.terrainOgreWin.LoadTerrain(filename) + self.tb1.EnableTool(ID_SaveTerrain, True) + self.tb1.EnableTool(ID_SaveTerrainAs, True) + + + def OnSaveTerrain(self, event=None): if not self.terrainOgreWin.SaveTerrain(): dlg = wx.MessageDialog(self, "error while saving, see console!\n","error", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() - def OnFileSaveAs(self, event): + def OnSaveTerrainAs(self, event=None): default = "" if self.rordir: default = os.path.join(self.rordir, TERRAINDIR) @@ -277,136 +319,227 @@ dlg.ShowModal() dlg.Destroy() + def OnPaneClose(self, event): + caption = event.GetPane().caption - def OnFileOpen(self, event=None): - default = "" - if self.rordir: - default = os.path.join(self.rordir, TERRAINDIR) - #print default - dialog = wx.FileDialog(self, "Open Terrain", default, "", "Terrain Files (*.terrn)|*.terrn", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) - res = dialog.ShowModal() - if res == wx.ID_OK: - #self.fileopenmenu.Enable(False) - self.filesavemenu.Enable(True) - self.filesaveasmenu.Enable(True) - filename = dialog.GetPath() - - self.terrainOgreWin.LoadTerrain(filename) - if not self.terrainOgreWin.terrain is None: - #update some controls if finished loading - self.waterlevelctrl.SetValue(self.terrainOgreWin.terrain.WaterHeight) - self.waterLevelText.Label = "Water Level: %0.1f" % (self.terrainOgreWin.terrain.WaterHeight) - self.terrainNamectrl.SetValue(self.terrainOgreWin.terrain.TerrainName) + if caption in ["Tree Pane", "Dock Manager Settings", "Fixed Pane"]: + msg = "Are You Sure You Want To Close This Pane?" + dlg = wx.MessageDialog(self, msg, "AUI Question", + wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) - - def onViewObjectDetails(self, event=None): - # split/unsplit - if self.viewObjectDetails.IsChecked(): - self.viewObjectDetails.Check(True) - self.splitter.SetSashPosition(600, True) - self.splitter.SplitVertically(self.splitterleft, self.splitterright) - else: - self.viewObjectDetails.Check(False) - self.splitter.Unsplit() + if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]: + event.Veto() + dlg.Destroy() - def onUpdateRender(self, event=None): - getOgreManager().RenderAll() - pass - def OnTimer(self, event): - #fill labels with some information, all windows have the same FPS! - txt = "%0.2f FPS" % (self.terrainOgreWin.renderWindow.getStatistics().lastFPS) - self.statusbar.SetStatusText(txt, 4) - self.updateObjPosRot() - + def OnClose(self, event): + self._mgr.UnInit() + del self._mgr + self.Destroy() + + def OnExit(self, event): - self.Close(True) - del self - sys.exit(0) - - def __set_properties(self): - try: - import ror.svn - self.SetTitle("RoR Terrain Editor revision %d" % ror.svn.getRevision()) - except: - self.SetTitle("RoR Terrain Editor") - - self.terrainOgreWin.SetMinSize((640,480)) + self.Close() - def __do_layout(self): - sizer_main = wx.BoxSizer(wx.HORIZONTAL) + def OnAbout(self, event): + ShowOnAbout() - sizer_left = wx.BoxSizer(wx.VERTICAL) - sizer_left.Add(self.terrainOgreWin, 2, wx.EXPAND, 0) - self.splitterleft.SetSizer(sizer_left) + def GetDockArt(self): + return self._mgr.GetArtProvider() - - #construct view boxes - sizerviewup = wx.BoxSizer(wx.VERTICAL) - #sizerviewup.Add(self.rotatingLabel, 0, wx.EXPAND, 0) - sizerviewup.Add(self.sharedOgreWin, 1, wx.EXPAND, 0) - self.viewsplitterup.SetSizer(sizerviewup) - sizerviewdown = wx.BoxSizer(wx.VERTICAL) - #sizerviewdown.Add(self.topLabel, 0, wx.EXPAND, 0) - sizerviewdown.Add(self.sharedOgreWin2, 1, wx.EXPAND, 0) - self.viewsplitterdown.SetSizer(sizerviewdown) - self.viewsplitter.SplitHorizontally(self.viewsplitterup, self.viewsplitterdown) + def DoUpdate(self): + self._mgr.Update() - - sizer_right = wx.BoxSizer(wx.VERTICAL) - sizer_right.Add(self.viewsplitter, 1, wx.EXPAND, 0) - self.splitterright.SetSizer(sizer_right) + def OnEraseBackground(self, event): + event.Skip() - self.splitter.SplitVertically(self.splitterleft, self.splitterright) - self.splitter.Unsplit() - self.splitter.SetSashPosition(600) + def OnSize(self, event): + event.Skip() + + + def OnSettings(self, event): + # show the settings pane, and float it + floating_pane = self._mgr.GetPane("settings").Float().Show() + + if floating_pane.floating_pos == wx.DefaultPosition: + floating_pane.FloatingPosition(self.GetStartPosition()) + + self._mgr.Update() + + def managerInit(self): + flags = self._mgr.GetFlags() + # based on default settings! + flags |= wx.aui.AUI_MGR_ALLOW_ACTIVE_PANE + flags &= ~wx.aui.AUI_MGR_TRANSPARENT_DRAG + self._mgr.SetFlags(flags) + + def OnCreatePerspective(self, event): + dlg = wx.TextEntryDialog(self, "Enter a name for the new perspective:", "AUI Test") - sizer_main.Add(self.splitter, 1, wx.EXPAND, 0) + dlg.SetValue(("Perspective %d")%(len(self._perspectives)+1)) + if dlg.ShowModal() != wx.ID_OK: + return + + if len(self._perspectives) == 0: + self._perspectives_menu.AppendSeparator() + + self._perspectives_menu.Append(ID_FirstPerspective + len(self._perspectives), dlg.GetValue()) + self._perspectives.append(self._mgr.SavePerspective()) - sizer_settings = wx.BoxSizer(wx.VERTICAL) - sizer_settings.Add(self.waterLevelText, 0, wx.EXPAND, 0) - sizer_settings.Add(self.waterlevelctrl, 0, wx.EXPAND, 0) - sizer_settings.Add(self.terrainName, 0, wx.EXPAND, 0) - sizer_settings.Add(self.terrainNamectrl, 0, wx.EXPAND, 0) + def OnCopyPerspective(self, event): + s = self._mgr.SavePerspective() - #sizer_settings.Add(self.CurrEntName, 0, wx.EXPAND, 0) - #sizer_settings.Add(self.PosText, 0, wx.EXPAND, 0) - #sizer_terrPos = wx.BoxSizer(wx.HORIZONTAL) - #sizer_terrPos.Add(self.terrPosX, 0, wx.EXPAND, 0) - #sizer_terrPos.Add(self.terrPosY, 0, wx.EXPAND, 0) - #sizer_terrPos.Add(self.terrPosZ, 0, wx.EXPAND, 0) - #sizer_settings.Add(sizer_terrPos, 0, wx.EXPAND, 0) + if wx.TheClipboard.Open(): - #sizer_settings.Add(self.RotText, 0, wx.EXPAND, 0) - #sizer_terrRot = wx.BoxSizer(wx.HORIZONTAL) - #sizer_terrRot.Add(self.terrRotX, 0, wx.EXPAND, 0) - #sizer_terrRot.Add(self.terrRotY, 0, wx.EXPAND, 0) - #sizer_terrRot.Add(self.terrRotZ, 0, wx.EXPAND, 0) - #sizer_settings.Add(sizer_terrRot, 0, wx.EXPAND, 0) + wx.TheClipboard.SetData(wx.TextDataObject(s)) + wx.TheClipboard.Close() - sizer_settings.Add(self.btnResetRotation, 0, wx.EXPAND, 0) - sizer_settings.Add(self.btnStickToGround, 0, wx.EXPAND, 0) + def OnRestorePerspective(self, event): + self._mgr.LoadPerspective(self._perspectives[event.GetId() - ID_FirstPerspective]) + + + def GetStartPosition(self): + self.x = self.x + 20 + x = self.x + pt = self.ClientToScreen(wx.Point(0, 0)) + return wx.Point(pt.x + x, pt.y + x) + + + def OnCreateTree(self, event): + self._mgr.AddPane(self.CreateTreeCtrl(), wx.aui.AuiPaneInfo(). + Caption("Tree Control"). + Float().FloatingPosition(self.GetStartPosition()). + FloatingSize(wx.Size(150, 300)).CloseButton(True).MaximizeButton(True)) + self._mgr.Update() + + + def OnCreateGrid(self, event): + self._mgr.AddPane(self.CreateGrid(), wx.aui.AuiPaneInfo(). + Caption("Grid"). + Float().FloatingPosition(self.GetStartPosition()). + FloatingSize(wx.Size(300, 200)).CloseButton(True).MaximizeButton(True)) + self._mgr.Update() + + + def OnCreateHTML(self, event): + self._mgr.AddPane(self.CreateHTMLCtrl(), wx.aui.AuiPaneInfo(). + Caption("HTML Content"). + Float().FloatingPosition(self.GetStartPosition()). + FloatingSize(wx.Size(300, 200)).CloseButton(True).MaximizeButton(True)) + self._mgr.Update() + + + def OnCreateText(self, event): + self._mgr.AddPane(self.CreateTextCtrl(), wx.aui.AuiPaneInfo(). + Caption("Text Control"). + Float().FloatingPosition(self.GetStartPosition()). + CloseButton(True).MaximizeButton(True)) + self._mgr.Update() + + + def OnCreateSizeReport(self, event): + self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo(). + Caption("Client Size Reporter"). + Float().FloatingPosition(self.GetStartPosition()). + CloseButton(True).MaximizeButton(True)) + self._mgr.Update() + + + def OnChangeContentPane(self, event): + + self._mgr.GetPane("grid_content").Show(event.GetId() == ID_GridContent) + self._mgr.GetPane("text_content").Show(event.GetId() == ID_TextContent) + self._mgr.GetPane("tree_content").Show(event.GetId() == ID_TreeContent) + self._mgr.GetPane("sizereport_content").Show(event.GetId() == ID_SizeReportContent) + self._mgr.GetPane("html_content").Show(event.GetId() == ID_HTMLContent) + self._mgr.Update() + + def OnCreateOgre(self, event): + self._mgr.AddPane(self.CreateOgreCtrl(), wx.aui.AuiPaneInfo(). + Caption("Ogre Window"). + Float().FloatingPosition(self.GetStartPosition()). + CloseButton(True).MaximizeButton(True)) + self._mgr.Update() + - sizer_main.Add(sizer_settings, 0, wx.EXPAND, 0) + def CreateOgreCtrl(self): + return RoRTerrainOgreWindow(self, wx.ID_ANY, scenemanager=self.ogrewin.sceneManager) + + def CreateTextCtrl(self): + text = ("This is text box %d")%(self.n + 1) + return wx.TextCtrl(self,-1, text, wx.Point(0, 0), wx.Size(150, 90), + wx.NO_BORDER | wx.TE_MULTILINE) + + + + def CreateGrid(self): + grid = wx.grid.Grid(self, -1, wx.Point(0, 0), wx.Size(150, 250), + wx.NO_BORDER | wx.WANTS_CHARS) + grid.CreateGrid(50, 20) + return grid + + + def CreateTreeCtrl(self): + tree = wx.TreeCtrl(self, -1, wx.Point(0, 0), wx.Size(160, 250), + wx.TR_DEFAULT_STYLE | wx.NO_BORDER) - self.SetAutoLayout(True) - self.SetSizer(sizer_main) - sizer_main.Fit(self) - sizer_main.SetSizeHints(self) - self.Layout() + root = tree.AddRoot("AUI Project") + items = [] - + imglist = wx.ImageList(16, 16, True, 2) + imglist.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, wx.Size(16,16))) + imglist.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16,16))) + tree.AssignImageList(imglist) + + items.append(tree.AppendItem(root, "Item 1", 0)) + items.append(tree.AppendItem(root, "Item 2", 0)) + items.append(tree.AppendItem(root, "Item 3", 0)) + items.append(tree.AppendItem(root, "Item 4", 0)) + items.append(tree.AppendItem(root, "Item 5", 0)) + + for ii in xrange(len(items)): + + id = items[ii] + tree.AppendItem(id, "Subitem 1", 1) + tree.AppendItem(id, "Subitem 2", 1) + tree.AppendItem(id, "Subitem 3", 1) + tree.AppendItem(id, "Subitem 4", 1) + tree.AppendItem(id, "Subitem 5", 1) + + tree.Expand(root) + + return tree + + + def CreateSizeReportCtrl(self, width=80, height=80): + ctrl = SizeReportCtrl(self, -1, wx.DefaultPosition, + wx.Size(width, height), self._mgr) + return ctrl + + def CreateHTMLCtrl(self): + ctrl = wx.html.HtmlWindow(self, -1, wx.DefaultPosition, wx.Size(400, 300)) + if "gtk2" in wx.PlatformInfo: + ctrl.SetStandardFonts() + ctrl.SetPage(self.GetIntroText()) + return ctrl + + def GetIntroText(self): + return overview + def startApp(): MainApp = wx.PySimpleApp(0) wx.InitAllImageHandlers() #you may or may not need this myFrame = MainFrame(None, -1, "") MainApp.SetTopWindow(myFrame) + + myFrame.SetSize((800, 600)) + myFrame.SetFocus() myFrame.Show() MainApp.MainLoop() \ No newline at end of file Added: trunk/lib/rorterraineditor/MainFrame_Tools.py =================================================================== --- trunk/lib/rorterraineditor/MainFrame_Tools.py (rev 0) +++ trunk/lib/rorterraineditor/MainFrame_Tools.py 2007-08-01 12:09:55 UTC (rev 148) @@ -0,0 +1,417 @@ +import sys, os, os.path + +import wx +import wx.grid +import wx.html +import wx.aui + +import cStringIO +# -- wx.SizeReportCtrl -- +# (a utility control that always reports it's client size) + +class SizeReportCtrl(wx.PyControl): + + def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, + size=wx.DefaultSize, mgr=None): + + wx.PyControl.__init__(self, parent, id, pos, size, wx.NO_BORDER) + + self._mgr = mgr + + self.Bind(wx.EVT_PAINT, self.OnPaint) + self.Bind(wx.EVT_SIZE, self.OnSize) + self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) + + + def OnPaint(self, event): + + dc = wx.PaintDC(self) + + size = self.GetClientSize() + s = ("Size: %d x %d")%(size.x, size.y) + + dc.SetFont(wx.NORMAL_FONT) + w, height = dc.GetTextExtent(s) + height = height + 3 + dc.SetBrush(wx.WHITE_BRUSH) + dc.SetPen(wx.WHITE_PEN) + dc.DrawRectangle(0, 0, size.x, size.y) + dc.SetPen(wx.LIGHT_GREY_PEN) + dc.DrawLine(0, 0, size.x, size.y) + dc.DrawLine(0, size.y, size.x, 0) + dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)) + + if self._mgr: + + pi = self._mgr.GetPane(self) + + s = ("Layer: %d")%pi.dock_layer + w, h = dc.GetTextExtent(s) + dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)+(height*1)) + + s = ("Dock: %d Row: %d")%(pi.dock_direction, pi.dock_row) + w, h = dc.GetTextExtent(s) + dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)+(height*2)) + + s = ("Position: %d")%pi.dock_pos + w, h = dc.GetTextExtent(s) + dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)+(height*3)) + + s = ("Proportion: %d")%pi.dock_proportion + w, h = dc.GetTextExtent(s) + dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)+(height*4)) + + + def OnEraseBackground(self, event): + # intentionally empty + pass + + + def OnSize(self, event): + + self.Refresh() + event.Skip() + + +ID_PaneBorderSize = wx.ID_HIGHEST + 1 +ID_SashSize = ID_PaneBorderSize + 1 +ID_CaptionSize = ID_PaneBorderSize + 2 +ID_BackgroundColor = ID_PaneBorderSize + 3 +ID_SashColor = ID_PaneBorderSize + 4 +ID_InactiveCaptionColor = ID_PaneBorderSize + 5 +ID_InactiveCaptionGradientColor = ID_PaneBorderSize + 6 +ID_InactiveCaptionTextColor = ID_PaneBorderSize + 7 +ID_ActiveCaptionColor = ID_PaneBorderSize + 8 +ID_ActiveCaptionGradientColor = ID_PaneBorderSize + 9 +ID_ActiveCaptionTextColor = ID_PaneBorderSize + 10 +ID_BorderColor = ID_PaneBorderSize + 11 +ID_GripperColor = ID_PaneBorderSize + 12 + +class SettingsPanel(wx.Panel): + + def __init__(self, parent, frame): + + wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, + wx.DefaultSize) + + self._frame = frame + + vert = wx.BoxSizer(wx.VERTICAL) + + s1 = wx.BoxSizer(wx.HORIZONTAL) + self._border_size = wx.SpinCtrl(self, ID_PaneBorderSize, "", wx.DefaultPosition, wx.Size(50,20)) + s1.Add((1, 1), 1, wx.EXPAND) + s1.Add(wx.StaticText(self, -1, "Pane Border Size:")) + s1.Add(self._border_size) + s1.Add((1, 1), 1, wx.EXPAND) + s1.SetItemMinSize(1, (180, 20)) + #vert.Add(s1, 0, wx.EXPAND | wxLEFT | wxBOTTOM, 5) + + s2 = wx.BoxSizer(wx.HORIZONTAL) + self._sash_size = wx.SpinCtrl(self, ID_SashSize, "", wx.DefaultPosition, wx.Size(50,20)) + s2.Add((1, 1), 1, wx.EXPAND) + s2.Add(wx.StaticText(self, -1, "Sash Size:")) + s2.Add(self._sash_size) + s2.Add((1, 1), 1, wx.EXPAND) + s2.SetItemMinSize(1, (180, 20)) + #vert.Add(s2, 0, wx.EXPAND | wxLEFT | wxBOTTOM, 5) + + s3 = wx.BoxSizer(wx.HORIZONTAL) + self._caption_size = wx.SpinCtrl(self, ID_CaptionSize, "", wx.DefaultPosition, wx.Size(50,20)) + s3.Add((1, 1), 1, wx.EXPAND) + s3.Add(wx.StaticText(self, -1, "Caption Size:")) + s3.Add(self._caption_size) + s3.Add((1, 1), 1, wx.EXPAND) + s3.SetItemMinSize(1, (180, 20)) + #vert.Add(s3, 0, wx.EXPAND | wxLEFT | wxBOTTOM, 5) + + #vert.Add(1, 1, 1, wx.EXPAND) + + b = self.CreateColorBitmap(wx.BLACK) + + s4 = wx.BoxSizer(wx.HORIZONTAL) + self._background_color = wx.BitmapButton(self, ID_BackgroundColor, b, wx.DefaultPosition, wx.Size(50,25)) + s4.Add((1, 1), 1, wx.EXPAND) + s4.Add(wx.StaticText(self, -1, "Background Color:")) + s4.Add(self._background_color) + s4.Add((1, 1), 1, wx.EXPAND) + s4.SetItemMinSize(1, (180, 20)) + + s5 = wx.BoxSizer(wx.HORIZONTAL) + self._sash_color = wx.BitmapButton(self, ID_SashColor, b, wx.DefaultPosition, wx.Size(50,25)) + s5.Add((1, 1), 1, wx.EXPAND) + s5.Add(wx.StaticText(self, -1, "Sash Color:")) + s5.Add(self._sash_color) + s5.Add((1, 1), 1, wx.EXPAND) + s5.SetItemMinSize(1, (180, 20)) + + s6 = wx.BoxSizer(wx.HORIZONTAL) + self._inactive_caption_color = wx.BitmapButton(self, ID_InactiveCaptionColor, b, + wx.DefaultPosition, wx.Size(50,25)) + s6.Add((1, 1), 1, wx.EXPAND) + s6.Add(wx.StaticText(self, -1, "Normal Caption:")) + s6.Add(self._inactive_caption_color) + s6.Add((1, 1), 1, wx.EXPAND) + s6.SetItemMinSize(1, (180, 20)) + + s7 = wx.BoxSizer(wx.HORIZONTAL) + self._inactive_caption_gradient_color = wx.BitmapButton(self, ID_InactiveCaptionGradientColor, + b, wx.DefaultPosition, wx.Size(50,25)) + s7.Add((1, 1), 1, wx.EXPAND) + s7.Add(wx.StaticText(self, -1, "Normal Caption Gradient:")) + s7.Add(self._inactive_caption_gradient_color) + s7.Add((1, 1), 1, wx.EXPAND) + s7.SetItemMinSize(1, (180, 20)) + + s8 = wx.BoxSizer(wx.HORIZONTAL) + self._inactive_caption_text_color = wx.BitmapButton(self, ID_InactiveCaptionTextColor, b, + wx.DefaultPosition, wx.Size(50,25)) + s8.Add((1, 1), 1, wx.EXPAND) + s8.Add(wx.StaticText(self, -1, "Normal Caption Text:")) + s8.Add(self._inactive_caption_text_color) + s8.Add((1, 1), 1, wx.EXPAND) + s8.SetItemMinSize(1, (180, 20)) + + s9 = wx.BoxSizer(wx.HORIZONTAL) + self._active_caption_color = wx.BitmapButton(self, ID_ActiveCaptionColor, b, + wx.DefaultPosition, wx.Size(50,25)) + s9.Add((1, 1), 1, wx.EXPAND) + s9.Add(wx.StaticText(self, -1, "Active Caption:")) + s9.Add(self._active_caption_color) + s9.Add((1, 1), 1, wx.EXPAND) + s9.SetItemMinSize(1, (180, 20)) + + s10 = wx.BoxSizer(wx.HORIZONTAL) + self._active_caption_gradient_color = wx.BitmapButton(self, ID_ActiveCaptionGradientColor, + b, wx.DefaultPosition, wx.Size(50,25)) + s10.Add((1, 1), 1, wx.EXPAND) + s10.Add(wx.StaticText(self, -1, "Active Caption Gradient:")) + s10.Add(self._active_caption_gradient_color) + s10.Add((1, 1), 1, wx.EXPAND) + s10.SetItemMinSize(1, (180, 20)) + + s11 = wx.BoxSizer(wx.HORIZONTAL) + self._active_caption_text_color = wx.BitmapButton(self, ID_ActiveCaptionTextColor, + b, wx.DefaultPosition, wx.Size(50,25)) + s11.Add((1, 1), 1, wx.EXPAND) + s11.Add(wx.StaticText(self, -1, "Active Caption Text:")) + s11.Add(self._active_caption_text_color) + s11.Add((1, 1), 1, wx.EXPAND) + s11.SetItemMinSize(1, (180, 20)) + + s12 = wx.BoxSizer(wx.HORIZONTAL) + self._border_color = wx.BitmapButton(self, ID_BorderColor, b, wx.DefaultPosition, + wx.Size(50,25)) + s12.Add((1, 1), 1, wx.EXPAND) + s12.Add(wx.StaticText(self, -1, "Border Color:")) + s12.Add(self._border_color) + s12.Add((1, 1), 1, wx.EXPAND) + s12.SetItemMinSize(1, (180, 20)) + + s13 = wx.BoxSizer(wx.HORIZONTAL) + self._gripper_color = wx.BitmapButton(self, ID_GripperColor, b, wx.DefaultPosition, + wx.Size(50,25)) + s13.Add((1, 1), 1, wx.EXPAND) + s13.Add(wx.StaticText(self, -1, "Gripper Color:")) + s13.Add(self._gripper_color) + s13.Add((1, 1), 1, wx.EXPAND) + s13.SetItemMinSize(1, (180, 20)) + + grid_sizer = wx.GridSizer(0, 2) + grid_sizer.SetHGap(5) + grid_sizer.Add(s1) + grid_sizer.Add(s4) + grid_sizer.Add(s2) + grid_sizer.Add(s5) + grid_sizer.Add(s3) + grid_sizer.Add(s13) + grid_sizer.Add((1, 1)) + grid_sizer.Add(s12) + grid_sizer.Add(s6) + grid_sizer.Add(s9) + grid_sizer.Add(s7) + grid_sizer.Add(s10) + grid_sizer.Add(s8) + grid_sizer.Add(s11) + + cont_sizer = wx.BoxSizer(wx.VERTICAL) + cont_sizer.Add(grid_sizer, 1, wx.EXPAND | wx.ALL, 5) + self.SetSizer(cont_sizer) + self.GetSizer().SetSizeHints(self) + + self._border_size.SetValue(frame.GetDockArt().GetMetric(wx.aui.AUI_DOCKART_PANE_BORDER_SIZE)) + self._sash_size.SetValue(frame.GetDockArt().GetMetric(wx.aui.AUI_DOCKART_SASH_SIZE)) + self._caption_size.SetValue(frame.GetDockArt().GetMetric(wx.aui.AUI_DOCKART_CAPTION_SIZE)) + + self.UpdateColors() + + self.Bind(wx.EVT_SPINCTRL, self.OnPaneBorderSize, id=ID_PaneBorderSize) + self.Bind(wx.EVT_SPINCTRL, self.OnSashSize, id=ID_SashSize) + self.Bind(wx.EVT_SPINCTRL, self.OnCaptionSize, id=ID_CaptionSize) + self.Bind(wx.EVT_BUTTON, self.OnSetColor, id=ID_BackgroundColor) + self.Bind(wx.EVT_BUTTON, self.OnSetColor, id=ID_SashColor) + self.Bind(wx.EVT_BUTTON, self.OnSetColor, id=ID_InactiveCaptionColor) + self.Bind(wx.EVT_BUTTON, self.OnSetColor, id=ID_InactiveCaptionGradientColor) + self.Bind(wx.EVT_BUTTON, self.OnSetColor, id=ID_InactiveCaptionTextColor) + self.Bind(wx.EVT_BUTTON, self.OnSetColor, id=ID_ActiveCaptionColor) + self.Bind(wx.EVT_BUTTON, self.OnSetColor, id=ID_ActiveCaptionGradientColor) + self.Bind(wx.EVT_BUTTON, self.OnSetColor, id=ID_ActiveCaptionTextColor) + self.Bind(wx.EVT_BUTTON, self.OnSetColor, id=ID_BorderColor) + self.Bind(wx.EVT_BUTTON, self.OnSetColor, id=ID_GripperColor) + + + def CreateColorBitmap(self, c): + image = wx.EmptyImage(25, 14) + + for x in xrange(25): + for y in xrange(14): + pixcol = c + if x == 0 or x == 24 or y == 0 or y == 13: + pixcol = wx.BLACK + + image.SetRGB(x, y, pixcol.Red(), pixcol.Green(), pixcol.Blue()) + + return image.ConvertToBitmap() + + + def UpdateColors(self): + + bk = self._frame.GetDockArt().GetColour(wx.aui.AUI_DOCKART_BACKGROUND_COLOUR) + self._background_color.SetBitmapLabel(self.CreateColorBitmap(bk)) + + cap = self._frame.GetDockArt().GetColour(wx.aui.AUI_DOCKART_INACTIVE_CAPTION_COLOUR) + self._inactive_caption_color.SetBitmapLabel(self.CreateColorBitmap(cap)) + + capgrad = self._frame.GetDockArt().GetColour(wx.aui.AUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR) + self._inactive_caption_gradient_color.SetBitmapLabel(self.CreateColorBitmap(capgrad)) + + captxt = self._frame.GetDockArt().GetColour(wx.aui.AUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR) + self._inactive_caption_text_color.SetBitmapLabel(self.CreateColorBitmap(captxt)) + + acap = self._frame.GetDockArt().GetColour(wx.aui.AUI_DOCKART_ACTIVE_CAPTION_COLOUR) + self._active_caption_color.SetBitmapLabel(self.CreateColorBitmap(acap)) + + acapgrad = self._frame.GetDockArt().GetColour(wx.aui.AUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR) + self._active_caption_gradient_color.SetBitmapLabel(self.CreateColorBitmap(acapgrad)) + + acaptxt = self._frame.GetDockArt().GetColour(wx.aui.AUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR) + self._active_caption_text_color.SetBitmapLabel(self.CreateColorBitmap(acaptxt)) + + sash = self._frame.GetDockArt().GetColour(wx.aui.AUI_DOCKART_SASH_COLOUR) + self._sash_color.SetBitmapLabel(self.CreateColorBitmap(sash)) + + border = self._frame.GetDockArt().GetColour(wx.aui.AUI_DOCKART_BORDER_COLOUR) + self._border_color.SetBitmapLabel(self.CreateColorBitmap(border)) + + gripper = self._frame.GetDockArt().GetColour(wx.aui.AUI_DOCKART_GRIPPER_COLOUR) + self._gripper_color.SetBitmapLabel(self.CreateColorBitmap(gripper)) + + + def OnPaneBorderSize(self, event): + + self._frame.GetDockArt().SetMetric(wx.aui.AUI_DOCKART_PANE_BORDER_SIZE, + event.GetInt()) + self._frame.DoUpdate() + + + def OnSashSize(self, event): + + self._frame.GetDockArt().SetMetric(wx.aui.AUI_DOCKART_SASH_SIZE, + event.GetInt()) + self._frame.DoUpdate() + + + def OnCaptionSize(self, event): + + self._frame.GetDockArt().SetMetric(wx.aui.AUI_DOCKART_CAPTION_SIZE, + event.GetInt()) + self._frame.DoUpdate() + + + def OnSetColor(self, event): + + dlg = wx.ColourDialog(self._frame) + + dlg.SetTitle("Color Picker") + + if dlg.ShowModal() != wx.ID_OK: + return + + var = 0 + if event.GetId() == ID_BackgroundColor: + var = wx.aui.AUI_DOCKART_BACKGROUND_COLOUR + elif event.GetId() == ID_SashColor: + var = wx.aui.AUI_DOCKART_SASH_COLOUR + elif event.GetId() == ID_InactiveCaptionColor: + var = wx.aui.AUI_DOCKART_INACTIVE_CAPTION_COLOUR + elif event.GetId() == ID_InactiveCaptionGradientColor: + var = wx.aui.AUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR + elif event.GetId() == ID_InactiveCaptionTextColor: + var = wx.aui.AUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR + elif event.GetId() == ID_ActiveCaptionColor: + var = wx.aui.AUI_DOCKART_ACTIVE_CAPTION_COLOUR + elif event.GetId() == ID_ActiveCaptionGradientColor: + var = wx.aui.AUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR + elif event.GetId() == ID_ActiveCaptionTextColor: + var = wx.aui.AUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR + elif event.GetId() == ID_BorderColor: + var = wx.aui.AUI_DOCKART_BORDER_COLOUR + elif event.GetId() == ID_GripperColor: + var = wx.aui.AUI_DOCKART_GRIPPER_COLOUR + else: + return + + self._frame.GetDockArt().SetColor(var, dlg.GetColourData().GetColour()) + self._frame.DoUpdate() + self.UpdateColors() + + + +#---------------------------------------------------------------------- + +class TestPanel(wx.Panel): + def __init__(self, parent, log): + self.log = log + wx.Panel.__init__(self, parent, -1) + b = wx.Button(self, -1, "Show the wx.aui Demo Frame", (50,50)) + self.Bind(wx.EVT_BUTTON, self.OnButton, b) + + def OnButton(self, evt): + frame = PyAUIFrame(self, wx.ID_ANY, "wx.aui wxPython Demo", size=(750, 590)) + frame.Show() + +#---------------------------------------------------------------------- + +def runTest(frame, nb, log): + win = TestPanel(nb, log) + return win + +#---------------------------------------------------------------------- + + + +overview = """\ +<html><body> +<h3>wx.aui, the Advanced User Interface module</h3> + +<br/><b>Overview</b><br/> + +<p>wx.aui is an Advanced User Interface library for the wxWidgets toolkit +that allows developers to create high-quality, cross-platform user +interfaces quickly and easily.</p> + +<p><b>Features</b></p> + +<p>With wx.aui developers can create application frameworks with:</p> + +<ul> +<li>Native, dockable floating frames</li> +<li>Perspective saving and loading</li> +<li>Native toolbars incorporating real-time, "spring-loaded" dragging</li> +<li>Customizable floating/docking behavior</li> +<li>Completely customizable look-and-feel</li> +<li>Optional transparent window effects (while dragging or docking)</li> +</ul> + +</body></html> +""" \ No newline at end of file Modified: trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py =================================================================== --- trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py 2007-07-29 16:07:10 UTC (rev 147) +++ trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py 2007-08-01 12:09:55 UTC (rev 148) @@ -58,9 +58,9 @@ RotateNode = None stickCurrentObjectToGround = False - def __init__(self, parent, ID, size = wx.Size(200,200), rordir = "", **kwargs): + def __init__(self, parent, ID, size = wx.Size(200,200), rordir = "", scenemanager=None, **kwargs): self.rordir = rordir - + self.sceneManager = scenemanager self.parent = parent self.size = size self.kwargs = kwargs @@ -140,20 +140,22 @@ def SceneInitialisation(self): - addresources = [self.rordir+"\\data\\terrains",self.rordir+"\\data\\trucks",self.rordir+"\\data\\objects"] - # only init things in the main window, not in shared ones! - # setup resources - for r in addresources: - ogre.ResourceGroupManager.getSingleton().addResourceLocation(r, "FileSystem", "General", False) + hasparent = (not self.sceneManager is None) + if not hasparent: + addresources = [self.rordir+"\\data\\terrains",self.rordir+"\\data\\trucks",self.rordir+"\\data\\objects"] + # only init things in the main window, not in shared ones! + # setup resources + for r in addresources: + ogre.ResourceGroupManager.getSingleton().addResourceLocation(r, "FileSystem", "General", False) - ogre.ResourceGroupManager.getSingleton().addResourceLocation("media/packs/OgreCore.zip", "Zip", "Bootstrap", False) - ogre.ResourceGroupManager.getSingleton().addResourceLocation("media", "FileSystem", "General", False) - ogre.ResourceGroupManager.getSingleton().addResourceLocation("media/materials", "FileSystem", "General", False) - ogre.ResourceGroupManager.getSingleton().addResourceLocation("media/models", "FileSystem", "General", False) - ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups() + ogre.ResourceGroupManager.getSingleton().addResourceLocation("media/packs/OgreCore.zip", "Zip", "Bootstrap", False) + ogre.ResourceGroupManager.getSingleton().addResourceLocation("media", "FileSystem", "General", False) + ogre.ResourceGroupManager.getSingleton().addResourceLocation("media/materials", "FileSystem", "General", False) + ogre.ResourceGroupManager.getSingleton().addResourceLocation("media/models", "FileSystem", "General", False) + ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups() - #get the scenemanager - self.sceneManager = getOgreManager().createSceneManager(ogre.ST_EXTERIOR_CLOSE) + #get the scenemanager + self.sceneManager = getOgreManager().createSceneManager(ogre.ST_EXTERIOR_CLOSE) # create a camera cameraUUID = randomID() @@ -176,8 +178,9 @@ self.Bind(wx.EVT_KEY_UP, self.onKeyUp) self.Bind(wx.EVT_MOUSE_EVENTS, self.onMouseEvent) - #create objects - self.populateScene() + if not hasparent: + #create objects + self.populateScene() def updateWaterPlane(self): @@ -192,7 +195,7 @@ # see http://www.ogre3d.org/docs/api/html/classOgre_1_1MeshManager.html#Ogre_1_1MeshManagera5 waterid = str(randomID()) mesh = ogre.MeshManager.getSingleton().createPlane(waterid+'WaterPlane', "General", plane, 3000, 3000, - 20, 20, True, 1, 50.0, 50.0, ogre.Vector3(0, 0, 1), + 20, 20, True, 1, 200.0, 200.0, ogre.Vector3(0, 0, 1), ogre.HardwareBuffer.HBU_STATIC_WRITE_ONLY, ogre.HardwareBuffer.HBU_STATIC_WRITE_ONLY, True, True) Modified: trunk/media/materials/mysimple.material =================================================================== --- trunk/media/materials/mysimple.material 2007-07-29 16:07:10 UTC (rev 147) +++ trunk/media/materials/mysimple.material 2007-08-01 12:09:55 UTC (rev 148) @@ -10,7 +10,7 @@ { texture water.jpg scroll_anim 0.01 0.01 - alpha_op_ex source1 src_manual src_current 0.75 + alpha_op_ex source1 src_manual src_current 0.5 } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-08-03 00:39:50
|
Revision: 153 http://roreditor.svn.sourceforge.net/roreditor/?rev=153&view=rev Author: rorthomas Date: 2007-08-02 17:39:49 -0700 (Thu, 02 Aug 2007) Log Message: ----------- * improved SimpleTruckRepresentation.py, trucks and loads now have the correct texture! * fixed truck selection bug * removed unused materials Modified Paths: -------------- trunk/lib/ror/SimpleTruckRepresentation.py trunk/lib/rorterraineditor/RoRObjectPreviewOgreWindow.py trunk/media/materials/mysimple.material Modified: trunk/lib/ror/SimpleTruckRepresentation.py =================================================================== --- trunk/lib/ror/SimpleTruckRepresentation.py 2007-08-02 17:33:37 UTC (rev 152) +++ trunk/lib/ror/SimpleTruckRepresentation.py 2007-08-03 00:39:49 UTC (rev 153) @@ -19,6 +19,7 @@ return False try: + myManualObject = sceneManager.createManualObject(str(uuid)+"manual") #myManualObjectMaterial = ogre.MaterialManager.getSingleton().create("manualmaterial"+truckname+str(self.randomcounter),"debugger"); @@ -29,17 +30,86 @@ #myManualObjectMaterial.getTechnique(0).getPass(0).setSelfIllumination(0,0,1) #myManualObjectMaterial.getTechnique(0).getPass(0).setCullingMode(ogre.CULL_ANTICLOCKWISE) - matname = "" - if fn[-4:].lower() == "load": - matname = 'mysimple/loadcolor' - elif fn[-5:].lower() == "truck": - matname = 'mysimple/truckcolor' - + matname = "mysimple/water" + myManualObject.useIndexes = True myManualObject.estimateVertexCount(2000) myManualObject.estimateIndexCount(2000) - myManualObject.begin(matname+"grid", ogre.RenderOperation.OT_LINE_LIST) + minPos = ogre.Vector3(999,999,999) + maxPos = ogre.Vector3(-999,-999,-999) + matname = p.tree['globals'][0]['data'][2] + + if len(p.tree['submeshgroups']) > 0: + nodecounter = 0 + nodes = {} + myManualObject.begin(matname, ogre.RenderOperation.OT_TRIANGLE_LIST) + for nodeobj in p.tree['nodes']: + if nodeobj.has_key('type'): + continue + node = nodeobj['data'] + nodes[nodecounter] = [float(node[1]),float(node[2]),float(node[3])] + nodecounter +=1 + + # get min/max positions + if float(node[0]) < minPos.x: minPos.x = float(node[0]) + if float(node[1]) < minPos.y: minPos.y = float(node[1]) + if float(node[2]) < minPos.z: minPos.z = float(node[2]) + if float(node[0]) > maxPos.x: maxPos.x = float(node[0]) + if float(node[1]) > maxPos.y: maxPos.y = float(node[1]) + if float(node[2]) > maxPos.z: maxPos.z = float(node[2]) + + nodecounter = 0 + #print len(p.tree['submeshgroups']) + counter = 0 + if len(p.tree['submeshgroups']) > 0: + faces = [] + for smobj in p.tree['submeshgroups']: + uv = {} + for data in smobj['texcoords']: + tex = data['data'] + uv[int(tex[0])] = [float(tex[1]), float(tex[2])] + + for cabobj in smobj['cab']: + if cabobj.has_key('type'): + continue + cab = cabobj['data'] + #print "########face" + if cab != []: + try: + myManualObject.position(nodes[int(cab[2])]) + myManualObject.index(nodecounter) + nodecounter += 1 + myManualObject.textureCoord(uv[int(cab[2])][0], uv[int(cab[2])][1]) + + myManualObject.position(nodes[int(cab[1])]) + myManualObject.index(nodecounter) + nodecounter += 1 + + myManualObject.textureCoord(uv[int(cab[1])][0], uv[int(cab[1])][1]) + + myManualObject.position(nodes[int(cab[0])]) + myManualObject.index(nodecounter) + nodecounter += 1 + + myManualObject.textureCoord(uv[int(cab[0])][0], uv[int(cab[0])][1]) + + except: + print "error with cab: " + str(cab) + pass + else: + print "truck has no faces!" + + myManualObject.end() + myManualObject.setCastShadows(False) + mat = ogre.MaterialManager.getSingleton().getByName(matname) + if not mat is None: + mat.setCullingMode(ogre.CullingMode.CULL_NONE) + # create the mesh now + mesh = myManualObject.convertToMesh(str(uuid)+"manual") + + # add the lines! + myManualObject.begin(matname, ogre.RenderOperation.OT_LINE_LIST) for nodeobj in p.tree['nodes']: if nodeobj.has_key('type'): continue @@ -52,51 +122,16 @@ myManualObject.index(int(beam[0])) myManualObject.index(int(beam[1])) myManualObject.end() - myManualObject.begin(matname, ogre.RenderOperation.OT_TRIANGLE_LIST) - for nodeobj in p.tree['nodes']: - if nodeobj.has_key('type'): - continue - node = nodeobj['data'] - myManualObject.position(float(node[1]),float(node[2]),float(node[3])) - - #print len(p.tree['submeshgroups']) - if len(p.tree['submeshgroups']) > 0: - faces = [] - for smobj in p.tree['submeshgroups']: - for cabobj in smobj['cab']: - if cabobj.has_key('type'): - continue - cab = cabobj['data'] - #print "########face" - if cab != []: - try: - myManualObject.triangle(int(cab[0]),int(cab[1]),int(cab[2])) - except: - print "error with cab: " + str(cab) - pass - else: - print "truck has no faces!" - - myManualObject.end() + + entity = sceneManager.createEntity(str(uuid)+"entity", str(uuid)+"manual") + + myManualObjectNode = sceneManager.getRootSceneNode().createChildSceneNode(str(uuid)+"node") + newpos = (minPos+maxPos)/2 + #print "min:", minPos, "max:", maxPos, "newpos:", newpos + myManualObjectNode.setPosition(-newpos) + myManualObjectNode.attachObject(entity) + myManualObjectNode.attachObject(myManualObject) - try: - mesh = myManualObject.convertToMesh(str(uuid)+"manual") - entity = sceneManager.createEntity(str(uuid)+"entity", str(uuid)+"manual") - #trucknode = sceneManager.getRootSceneNode().createChildSceneNode() - myManualObjectNode = sceneManager.getRootSceneNode().createChildSceneNode(str(uuid)+"node") - myManualObjectNode.attachObject(myManualObject) - mesh = myManualObject.convertToMesh(str(uuid)+"manual") - entity = sceneManager.createEntity(str(uuid)+"entity", str(uuid)+"manual") - #trucknode = sceneManager.getRootSceneNode().createChildSceneNode() - myManualObjectNode = sceneManager.getRootSceneNode().createChildSceneNode(str(uuid)+"node") - myManualObjectNode.attachObject(entity) - myManualObjectNode.attachObject(myManualObject) - except: - mesh = None - entity = None - myManualObjectNode = sceneManager.getRootSceneNode().createChildSceneNode(str(uuid)+"node") - myManualObjectNode.attachObject(myManualObject) - return myManualObjectNode, entity, mesh except Exception, err: Modified: trunk/lib/rorterraineditor/RoRObjectPreviewOgreWindow.py =================================================================== --- trunk/lib/rorterraineditor/RoRObjectPreviewOgreWindow.py 2007-08-02 17:33:37 UTC (rev 152) +++ trunk/lib/rorterraineditor/RoRObjectPreviewOgreWindow.py 2007-08-03 00:39:49 UTC (rev 153) @@ -84,7 +84,6 @@ wx.WXK_DOWN:ogre.Vector3(0.0,0.0,d), wx.WXK_PAGEUP:ogre.Vector3(0.0,d,0.0), wx.WXK_PAGEDOWN:ogre.Vector3(0.0,-d,0.0)} - self.Bind(wx.EVT_KEY_DOWN, self.onKeyDown) self.Bind(wx.EVT_MOUSE_EVENTS, self.onMouseEvent) #create objects @@ -97,6 +96,7 @@ self.free() uuid = randomID() self.objnode, self.objentity, manualobject = createTruckMesh(self.sceneManager, filename, uuid) + print "aaa", self.objnode.getPosition() elif extension.lower() in [".odef"]: self.free() uuid = randomID() @@ -139,8 +139,8 @@ self.sceneManager.setShadowTechnique(ogre.ShadowTechnique.SHADOWTYPE_STENCIL_ADDITIVE); self.sceneManager.setSkyDome(True, 'mysimple/terraineditor/previewwindowsky', 4.0, 8.0) - self.MainLight = self.sceneManager.createLight('MainLight') - self.MainLight.setPosition (ogre.Vector3(20, 80, 130)) + #self.MainLight = self.sceneManager.createLight('MainLight') + #self.MainLight.setPosition (ogre.Vector3(20, 80, 130)) # add some fog self.sceneManager.setFog(ogre.FOG_EXP, ogre.ColourValue.White, 0.0002) @@ -163,13 +163,11 @@ def updateCamera(self): if not self.objnode is None: - if self.objentity is None: - self.radius = 15 - height = 2 - else: - self.radius = self.objentity.getBoundingRadius() * 2 - height = self.objentity.getBoundingBox().getMaximum().z - pos = self.objnode.getPosition() + ogre.Vector3(0, height*0.4, 0) + self.radius = self.objentity.getBoundingRadius() * 2 + height = self.objentity.getBoundingBox().getMaximum().z + #pos = self.objnode.getPosition() + ogre.Vector3(0, height*0.4, 0) + # always look to the center! + pos = self.objnode.getPosition() + ogre.Vector3(0, height*0.4, 0) + (self.objentity.getBoundingBox().getMinimum() + self.objentity.getBoundingBox().getMaximum() ) / 2 dx = math.cos(self.camalpha) * self.radius dy = math.sin(self.camalpha) * self.radius self.camera.setPosition(pos - ogre.Vector3(dx, -5, dy)) @@ -184,14 +182,6 @@ self.updateCamera() wxOgreWindow.OnFrameStarted(self) - def onKeyDown(self,event): - validMove = self.ControlKeyDict.get(event.m_keyCode, False) - if validMove: - pos = self.camera.getPosition() - pos += validMove - self.camera.setPosition(pos) - event.Skip() - def onMouseEvent(self, event): #self.SetFocus() #Gives Keyboard focus to the window Modified: trunk/media/materials/mysimple.material =================================================================== --- trunk/media/materials/mysimple.material 2007-08-02 17:33:37 UTC (rev 152) +++ trunk/media/materials/mysimple.material 2007-08-03 00:39:49 UTC (rev 153) @@ -36,85 +36,6 @@ } } -material mysimple/loadcolor -{ - technique - { - pass - { - lighting on - depth_check on - scene_blend alpha_blend - depth_write off - cull_hardware none - texture_unit - { - colour_op_ex source1 src_manual src_current 0.8 0.8 0 - alpha_op_ex source1 src_manual src_current 0.7 - } - } - } -} - -material mysimple/loadcolorgrid -{ - technique - { - pass - { - lighting on - depth_check on - scene_blend alpha_blend - depth_write off - cull_hardware none - texture_unit - { - colour_op_ex source1 src_manual src_current 1 1 0 - alpha_op_ex source1 src_manual src_current 1 - } - } - } -} - -material mysimple/truckcolor -{ - technique - { - pass - { - lighting on - depth_check on - scene_blend alpha_blend - depth_write off - cull_hardware none - texture_unit - { - colour_op_ex source1 src_manual src_current 0.8 0 0.8 - alpha_op_ex source1 src_manual src_current 0.7 - } - } - } -} -material mysimple/truckcolorgrid -{ - technique - { - pass - { - lighting on - depth_check on - scene_blend alpha_blend - depth_write off - cull_hardware none - texture_unit - { - colour_op_ex source1 src_manual src_current 1 0 1 - alpha_op_ex source1 src_manual src_current 1 - } - } - } -} - material mysimple/terrainselect { technique This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-08-08 01:34:36
|
Revision: 161 http://roreditor.svn.sourceforge.net/roreditor/?rev=161&view=rev Author: rorthomas Date: 2007-08-07 18:34:35 -0700 (Tue, 07 Aug 2007) Log Message: ----------- * added some nice logo :D Modified Paths: -------------- trunk/lib/roreditor/MainFrame_Tools.py trunk/lib/roreditor/RoRObjectPreviewOgreWindow.py Added Paths: ----------- trunk/lib/roreditor/help.html trunk/media/materials/odefeditor.material trunk/media/models/logotext.mesh trunk/media/models/logowheel.mesh Removed Paths: ------------- trunk/lib/roreditor/GUIPreviewObject.py trunk/lib/roreditor/MainFrame_old.py trunk/lib/roreditor/MainFrame_org.py trunk/lib/roreditor/terrainhelp.html Deleted: trunk/lib/roreditor/GUIPreviewObject.py =================================================================== --- trunk/lib/roreditor/GUIPreviewObject.py 2007-08-08 00:11:50 UTC (rev 160) +++ trunk/lib/roreditor/GUIPreviewObject.py 2007-08-08 01:34:35 UTC (rev 161) @@ -1,70 +0,0 @@ -import sys, os, os.path - -import wx -import wx.grid -import wx.html -import wx.aui -import ror.settingsManager - -import cStringIO - -RORPATH = ror.settingsManager.getSettingsManager().getSetting("RigsOfRods", "BasePath") -DATADIR = os.path.join(RORPATH, "data") -TRUCKDIR = os.path.join(DATADIR, "trucks") -TERRAINDIR = os.path.join(DATADIR, "terrains") -OBJECTDIR = os.path.join(DATADIR, "objects") - -class RoRObjectTreeCtrl(wx.Panel): - def __init__(self, parent, frame): - wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, - wx.DefaultSize) - - self._frame = frame - - - vert = wx.BoxSizer(wx.VERTICAL) - - - tree = wx.TreeCtrl(self, -1, wx.Point(0, 0), wx.DefaultSize, wx.NO_BORDER) - - root = tree.AddRoot("Objects") - items = [] - - imglist = wx.ImageList(16, 16, True, 2) - imglist.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, wx.Size(16,16))) - imglist.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16,16))) - tree.AssignImageList(imglist) - - trucks = self.getInstalledTrucks() - items.append(tree.AppendItem(root, "Trucks", 0)) - for truck in trucks: - truckname, extension = os.path.splitext(truck) - tree.AppendItem(items[-1], truckname, 1) - - objects = self.getInstalledObjects() - items.append(tree.AppendItem(root, "Objects", 0)) - for object in objects: - objectname, extension = os.path.splitext(object) - tree.AppendItem(items[-1], objectname, 1) - - - tree.Expand(root) - vert.Add(tree, 1, wx.EXPAND, 5) - self.SetSizer(vert) - self.GetSizer().SetSizeHints(self) - - def getInstalledTrucks(self): - files = [] - for filename in os.listdir(TRUCKDIR): - onlyfilename, extension = os.path.splitext(filename) - if extension.lower() == ".truck": - files.append(filename) - return files - - def getInstalledObjects(self): - files = [] - for filename in os.listdir(OBJECTDIR): - onlyfilename, extension = os.path.splitext(filename) - if extension.lower() == ".odef": - files.append(filename) - return files \ No newline at end of file Modified: trunk/lib/roreditor/MainFrame_Tools.py =================================================================== --- trunk/lib/roreditor/MainFrame_Tools.py 2007-08-08 00:11:50 UTC (rev 160) +++ trunk/lib/roreditor/MainFrame_Tools.py 2007-08-08 01:34:35 UTC (rev 161) @@ -12,7 +12,7 @@ # -- wx.SizeReportCtrl -- # (a utility control that always reports it's client size) -HELPFILENAME = os.path.join(os.path.dirname(os.path.abspath(__file__)), "terrainhelp.html") +HELPFILENAME = os.path.join(os.path.dirname(os.path.abspath(__file__)), "help.html") class HelpPanel(wx.Panel): def __init__(self, parent, frame): Deleted: trunk/lib/roreditor/MainFrame_old.py =================================================================== --- trunk/lib/roreditor/MainFrame_old.py 2007-08-08 00:11:50 UTC (rev 160) +++ trunk/lib/roreditor/MainFrame_old.py 2007-08-08 01:34:35 UTC (rev 161) @@ -1,412 +0,0 @@ -#Thomas Fischer 31/05/2007, th...@th... -from wxogre.OgreManager import * -from ror.RoROgreWindow import * - -from ror.logger import log -from ror.settingsManager import getSettingsManager - -from ror.rorcommon import * -from RoRTerrainOgreWindow import * -from RoRTerrainSelectedObjectOgreWindow import * -from RoRTerrainSelectedObjectTopOgreWindow import * - -ID_ABOUT = 101 -ID_OPENFILE = 102 -ID_SAVEFILE = 103 -ID_VIEWOBJ = 104 -ID_OGRESET = 105 -ID_SHOWHELP = 106 -ID_ADDTRUCK = 107 -ID_ADDMESH = 108 -ID_CHECKUPDATE = 109 -ID_SAVEFILEAS = 110 -ID_TERRAINCOLLISION = 111 -ID_EXIT = 199 - -DATADIR = "data" -TRUCKDIR = os.path.join(DATADIR, "trucks") -TERRAINDIR = os.path.join(DATADIR, "terrains") -OBJECTDIR = os.path.join(DATADIR, "objects") - - -class MainFrame(wx.Frame): - def __init__(self, *args, **kwds): - kwds["style"] = wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION | wx.CLIP_CHILDREN - - wx.Frame.__init__(self, *args, **kwds) - - - #main splitter - self.splitter = wx.SplitterWindow(self, wx.ID_ANY, style=wx.SP_PERMIT_UNSPLIT|wx.SP_3DSASH) - self.splitterleft = wx.Panel(self.splitter, wx.ID_ANY) - self.splitterright = wx.Panel(self.splitter, wx.ID_ANY) - self.splitter.SetSashGravity(1) - self.splitter.SetSashPosition(100) - self.splitter.SetMinimumPaneSize(200) - - #viewsplitter - self.viewsplitter = wx.SplitterWindow(self.splitterright, wx.ID_ANY) - self.viewsplitterup = wx.Panel(self.viewsplitter, wx.ID_ANY) - self.viewsplitterdown = wx.Panel(self.viewsplitter, wx.ID_ANY) - self.splitter.SetSashGravity(0.5) - self.splitter.SetSashPosition(100) - self.splitter.SetMinimumPaneSize(200) - - self.rordir = getSettingsManager().getSetting("RigsOfRods", "BasePath") - - #ogre windows - self.terrainOgreWin = RoRTerrainOgreWindow(self.splitterleft, wx.ID_ANY, rordir=self.rordir) - self.sharedOgreWin = RoRTerrainSelectedObjectOgreWindow(self.viewsplitterup, wx.ID_ANY, self.terrainOgreWin) - self.sharedOgreWin2 = RoRTerrainSelectedObjectTopOgreWindow(self.viewsplitterdown, wx.ID_ANY, self.terrainOgreWin) - - #some labels - #self.helptext = wx.StaticText(self.splitterleft, wx.ID_ANY, "short help: right click = rotate; ctrl + right click, AWSD, mouse wheel = move") - #self.rotatingLabel = wx.StaticText(self.viewsplitterup, wx.ID_ANY, "rotating") - #self.topLabel = wx.StaticText(self.viewsplitterdown, wx.ID_ANY, "top") - - #Timer creation (for label updates) - self.timer = wx.Timer() - self.timer.SetOwner(self) #Sets the timer to notify self: binding the timer event is not enough - self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) - self.timer.Start(200) - - #Timer creation (for rendering) - self.ogreTimer = wx.Timer() - self.ogreTimer.SetOwner(self) - self.Bind(wx.EVT_TIMER, self.onUpdateRender, self.ogreTimer) - self.ogreTimer.Start(25) - - #create statusbar - self.statusbar = self.CreateStatusBar(5, 0, wx.ID_ANY, "mainstatusbar") - self.statusbar.SetStatusWidths([-1, 200, 130, 250, 80]) - #self.statusbar.SetStatusText("", 1) - - #create toolbar - #self.toolbar = wx.ToolBar(self, wx.ID_ANY, style = wx.TB_HORZ_TEXT) - #self.SetToolBar(self.toolbar ) - #bitmap = wx.Bitmap("media/gui/OpenFile.gif", wx.BITMAP_TYPE_GIF) - #self.toolbar.DoAddTool(0, "Open Terrain", bitmap, bitmap, wx.ITEM_NORMAL, "Open Terrain", "Opens a new terrain for edit") - - #create general settings - #self.GeneralSettingsPanel = wx.Panel(self, wx.ID_ANY) - self.terrainName = wx.StaticText(self, wx.ID_ANY, "Terrain Name:") - self.terrainNamectrl = wx.TextCtrl(self, wx.ID_ANY) - self.Bind(wx.EVT_TEXT, self.OnChangeTerrainNameChange, self.terrainNamectrl) - - self.waterLevelText = wx.StaticText(self, wx.ID_ANY, "Water Level: 0") - self.waterlevelctrl = wx.Slider(self, wx.ID_ANY) - self.waterlevelctrl.max = 300 - self.Bind(wx.EVT_SCROLL, self.OnChangeWaterLevel, self.waterlevelctrl) - - #self.CurrEntName = wx.StaticText(self, wx.ID_ANY, "\n\n\n") - #self.PosText = wx.StaticText(self, wx.ID_ANY, "Position: x,y,z") - #self.terrPosX = wx.TextCtrl(self, wx.ID_ANY) - #self.terrPosY = wx.TextCtrl(self, wx.ID_ANY) - #self.terrPosZ = wx.TextCtrl(self, wx.ID_ANY) - #self.RotText = wx.StaticText(self, wx.ID_ANY, "Rotation: x,y,z") - #self.terrRotX = wx.TextCtrl(self, wx.ID_ANY) - #self.terrRotY = wx.TextCtrl(self, wx.ID_ANY) - #self.terrRotZ = wx.TextCtrl(self, wx.ID_ANY) - #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrPosX) - #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrPosY) - #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrPosZ) - #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrRotX) - #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrRotY) - #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrRotZ) - - self.btnResetRotation = wx.Button(self, wx.ID_ANY, "Reset Rotation") - self.Bind(wx.EVT_BUTTON, self.OnBtnResetRotation, self.btnResetRotation) - self.btnStickToGround = wx.ToggleButton(self, wx.ID_ANY, "Stick to Ground") - self.Bind(wx.EVT_TOGGLEBUTTON, self.OnBtnStickToGroundChange, self.btnStickToGround) - - - #menu creation - menuBar = wx.MenuBar() - file_menu = wx.Menu() - self.fileopenmenu = file_menu.Append(ID_OPENFILE, "&Open", "Open Terrain") - self.filesavemenu = file_menu.Append(ID_SAVEFILE, "&Save", "Save Terrain") - self.filesaveasmenu = file_menu.Append(ID_SAVEFILEAS, "&Save as", "Save Terrain as") - - self.filesavemenu.Enable(False) - self.filesaveasmenu.Enable(False) - file_menu.AppendSeparator() - file_menu.Append(ID_EXIT, "E&xit", "Terminate the program") - menuBar.Append(file_menu, "&File"); - - view_menu = wx.Menu() - self.mnuterraincollision = view_menu.AppendCheckItem(ID_TERRAINCOLLISION, "Camera collides with Terrain", "") - self.mnuterraincollision.Check(True) - view_menu.AppendSeparator() - self.viewObjectDetails = view_menu.AppendCheckItem(ID_VIEWOBJ, "&Additional Object View Window", "creates two additional views") - self.viewObjectDetails.Check(False) - view_menu.AppendSeparator() - view_menu.Append(ID_OGRESET, "&Ogre Settings", "Change Ogre Display Settings") - menuBar.Append(view_menu, "&View"); - - add_menu = wx.Menu() - add_menu.Append(ID_ADDTRUCK, "&Truck/Load", "add a Truck or a Load to the terrain") - self.Bind(wx.EVT_MENU, self.OnAddTruck, id=ID_ADDTRUCK) - add_menu.Append(ID_ADDMESH, "&Object", "add a static Object to the terrain") - self.Bind(wx.EVT_MENU, self.OnAddMesh, id=ID_ADDMESH) - menuBar.Append(add_menu, "&Add"); - - help_menu = wx.Menu() - help_menu.Append(ID_SHOWHELP, "Show &Help", "view the documentation") - help_menu.AppendSeparator() - help_menu.Append(ID_ABOUT, "&About", "More information about this program") - menuBar.Append(help_menu, "&Help"); - - #bindings - self.SetMenuBar(menuBar) - self.__set_properties() - self.__do_layout() - self.Bind(wx.EVT_MENU, self.OnExit, id=ID_EXIT) - self.Bind(wx.EVT_MENU, self.OnFileOpen, id=ID_OPENFILE) - self.Bind(wx.EVT_MENU, self.OnFileSave, id=ID_SAVEFILE) - self.Bind(wx.EVT_MENU, self.OnFileSaveAs, id=ID_SAVEFILEAS) - self.Bind(wx.EVT_MENU, self.OnAbout, id=ID_ABOUT) - self.Bind(wx.EVT_MENU, self.onViewObjectDetails, id=ID_VIEWOBJ) - self.Bind(wx.EVT_MENU, self.OnChangeOgreSettings, id=ID_OGRESET) - self.Bind(wx.EVT_MENU, self.OnCameraTerrainCollision, id=ID_TERRAINCOLLISION) - - def OnAbout(self, event=None): - ShowOnAbout() - - def OnCheckUpdate(self, event=None): - pass - - def OnCameraTerrainCollision(self, event=None): - self.terrainOgreWin.CameraLandCollision(self.mnuterraincollision.IsChecked()) - - def OnHelp(self, event=None): - import HelpFrame - HelpFrame.showHelpFrame() - - def OnAddTruck(self, event=None): - default = "" - if self.rordir: - default = os.path.join(self.rordir, TRUCKDIR) - dialog = wx.FileDialog(self, "Add Truck", default, "", "Truck and Load Files (*.truck,*.load)|*.truck;*.load", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) - res = dialog.ShowModal() - if res == wx.ID_OK: - if not self.terrainOgreWin.addTruckToTerrain(truckFilename=dialog.GetPath()): - dlg = wx.MessageDialog(self, "You must select a position on the ground first!", "error", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - - def OnAddMesh(self, event=None): - default = "" - if self.rordir: - default = os.path.join(self.rordir, OBJECTDIR) - dialog = wx.FileDialog(self, "Add Object", default, "", "RoR Object Definitions (*.odef)|*.odef", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) - res = dialog.ShowModal() - if res == wx.ID_OK: - if not self.terrainOgreWin.addObjectToTerrain(odefFilename=dialog.GetPath()): - dlg = wx.MessageDialog(self, "You must select a position on the ground first!", "error", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - - - def OnBtnResetRotation(self, event=None): - self.terrainOgreWin.ObjectResetRotation() - - def OnBtnStickToGroundChange(self, event=None): - self.terrainOgreWin.stickCurrentObjectToGround = self.btnStickToGround.GetValue() - - def updateObjPosRot(self, event=None): - self.statusbar.SetStatusText(self.terrainOgreWin.currentStatusMsg, 1) - if self.terrainOgreWin.terrain is None: - return - if self.terrainOgreWin.selectedEntry is None: - self.statusbar.SetStatusText("Nothing selected", 2) - return - entry = self.terrainOgreWin.selectedEntry - #comment = self.terrainOgreWin.getCommentsForObject(n.getName()).lstrip('/') - #if comment.strip() != "": - # txt = "%s / %s" % (n.getName(), comment) - #else: - txt = "%s %s" % (entry.data.name, " ".join(entry.data.additionaloptions)) - self.statusbar.SetStatusText(txt, 2) - - posx, posy, posz, rotx, roty, rotz = self.terrainOgreWin.getSelectionPositionRotation() - txt = "%0.2f, %0.2f, %0.2f / %0.2f, %0.2f, %0.2f" % (posx, posy, posz, rotx, roty, rotz) - self.statusbar.SetStatusText(txt, 3) - - #pos = n.getPosition() - #self.terrPosX.SetValue(str(round(pos.x,2))) - #self.terrPosY.SetValue(str(round(pos.y,2))) - #self.terrPosZ.SetValue(str(round(pos.z,2))) - #rot = n.getOrientation() - #self.terrRotX.SetValue(str(round(ogre.Radian(rot.getPitch(False)+90).valueDegrees(),2))) - #self.terrRotY.SetValue(str(round(ogre.Radian(rot.getYaw(False)).valueDegrees(),2))) - #self.terrRotZ.SetValue(str(round(ogre.Radian(rot.getRoll(False)).valueDegrees(),2))) - - #def OnChangeObjPosRot(self, event=None): - # pass - - def OnChangeTerrainNameChange(self, event=None): - self.terrainOgreWin.terrain.TerrainName = self.terrainNamectrl.GetValue() - - def OnChangeWaterLevel(self, event=None): - if not self.terrainOgreWin.terrain is None: - self.terrainOgreWin.terrain.WaterHeight = self.waterlevelctrl.GetValue() - self.waterLevelText.Label = "Water Level: %0.1f" % (self.terrainOgreWin.terrain.WaterHeight) - self.terrainOgreWin.updateWaterPlane() - - def OnChangeOgreSettings(self, event): - getOgreManager().getRoot().showConfigDialog() - dlg = wx.MessageDialog(self, "You must restart the program for the settings to get active", "Ogre Settings", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - - def OnFileSave(self, event): - if not self.terrainOgreWin.SaveTerrain(): - dlg = wx.MessageDialog(self, "error while saving, see console!\n","error", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - - def OnFileSaveAs(self, event): - default = "" - if self.rordir: - default = os.path.join(self.rordir, TERRAINDIR) - dialog = wx.FileDialog(self, "Save Terrain as", default, "", "Terrain Files (*.terrn)|*.terrn", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) - res = dialog.ShowModal() - if res == wx.ID_OK: - if not self.terrainOgreWin.SaveTerrain(dialog.GetPath()): - dlg = wx.MessageDialog(self, "error while saving as another file, see console!\n","error", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - - - def OnFileOpen(self, event=None): - default = "" - if self.rordir: - default = os.path.join(self.rordir, TERRAINDIR) - #print default - dialog = wx.FileDialog(self, "Open Terrain", default, "", "Terrain Files (*.terrn)|*.terrn", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) - res = dialog.ShowModal() - if res == wx.ID_OK: - #self.fileopenmenu.Enable(False) - self.filesavemenu.Enable(True) - self.filesaveasmenu.Enable(True) - filename = dialog.GetPath() - - self.terrainOgreWin.LoadTerrain(filename) - if not self.terrainOgreWin.terrain is None: - #update some controls if finished loading - self.waterlevelctrl.SetValue(self.terrainOgreWin.terrain.WaterHeight) - self.waterLevelText.Label = "Water Level: %0.1f" % (self.terrainOgreWin.terrain.WaterHeight) - self.terrainNamectrl.SetValue(self.terrainOgreWin.terrain.TerrainName) - - - def onViewObjectDetails(self, event=None): - # split/unsplit - if self.viewObjectDetails.IsChecked(): - self.viewObjectDetails.Check(True) - self.splitter.SetSashPosition(600, True) - self.splitter.SplitVertically(self.splitterleft, self.splitterright) - else: - self.viewObjectDetails.Check(False) - self.splitter.Unsplit() - - def onUpdateRender(self, event=None): - getOgreManager().RenderAll() - pass - - def OnTimer(self, event): - #fill labels with some information, all windows have the same FPS! - txt = "%0.2f FPS" % (self.terrainOgreWin.renderWindow.getStatistics().lastFPS) - self.statusbar.SetStatusText(txt, 4) - self.updateObjPosRot() - - def OnExit(self, event): - self.Close(True) - del self - sys.exit(0) - - def __set_properties(self): - try: - import ror.svn - self.SetTitle("RoR Terrain Editor revision %d" % ror.svn.getRevision()) - except: - self.SetTitle("RoR Terrain Editor") - - self.terrainOgreWin.SetMinSize((640,480)) - - def __do_layout(self): - sizer_main = wx.BoxSizer(wx.HORIZONTAL) - - sizer_left = wx.BoxSizer(wx.VERTICAL) - sizer_left.Add(self.terrainOgreWin, 2, wx.EXPAND, 0) - self.splitterleft.SetSizer(sizer_left) - - - #construct view boxes - sizerviewup = wx.BoxSizer(wx.VERTICAL) - #sizerviewup.Add(self.rotatingLabel, 0, wx.EXPAND, 0) - sizerviewup.Add(self.sharedOgreWin, 1, wx.EXPAND, 0) - self.viewsplitterup.SetSizer(sizerviewup) - - sizerviewdown = wx.BoxSizer(wx.VERTICAL) - #sizerviewdown.Add(self.topLabel, 0, wx.EXPAND, 0) - sizerviewdown.Add(self.sharedOgreWin2, 1, wx.EXPAND, 0) - self.viewsplitterdown.SetSizer(sizerviewdown) - self.viewsplitter.SplitHorizontally(self.viewsplitterup, self.viewsplitterdown) - - - sizer_right = wx.BoxSizer(wx.VERTICAL) - sizer_right.Add(self.viewsplitter, 1, wx.EXPAND, 0) - self.splitterright.SetSizer(sizer_right) - - - self.splitter.SplitVertically(self.splitterleft, self.splitterright) - self.splitter.Unsplit() - self.splitter.SetSashPosition(600) - - - sizer_main.Add(self.splitter, 1, wx.EXPAND, 0) - - - sizer_settings = wx.BoxSizer(wx.VERTICAL) - sizer_settings.Add(self.waterLevelText, 0, wx.EXPAND, 0) - sizer_settings.Add(self.waterlevelctrl, 0, wx.EXPAND, 0) - sizer_settings.Add(self.terrainName, 0, wx.EXPAND, 0) - sizer_settings.Add(self.terrainNamectrl, 0, wx.EXPAND, 0) - - #sizer_settings.Add(self.CurrEntName, 0, wx.EXPAND, 0) - #sizer_settings.Add(self.PosText, 0, wx.EXPAND, 0) - #sizer_terrPos = wx.BoxSizer(wx.HORIZONTAL) - #sizer_terrPos.Add(self.terrPosX, 0, wx.EXPAND, 0) - #sizer_terrPos.Add(self.terrPosY, 0, wx.EXPAND, 0) - #sizer_terrPos.Add(self.terrPosZ, 0, wx.EXPAND, 0) - #sizer_settings.Add(sizer_terrPos, 0, wx.EXPAND, 0) - - #sizer_settings.Add(self.RotText, 0, wx.EXPAND, 0) - #sizer_terrRot = wx.BoxSizer(wx.HORIZONTAL) - #sizer_terrRot.Add(self.terrRotX, 0, wx.EXPAND, 0) - #sizer_terrRot.Add(self.terrRotY, 0, wx.EXPAND, 0) - #sizer_terrRot.Add(self.terrRotZ, 0, wx.EXPAND, 0) - #sizer_settings.Add(sizer_terrRot, 0, wx.EXPAND, 0) - - sizer_settings.Add(self.btnResetRotation, 0, wx.EXPAND, 0) - sizer_settings.Add(self.btnStickToGround, 0, wx.EXPAND, 0) - - - sizer_main.Add(sizer_settings, 0, wx.EXPAND, 0) - - self.SetAutoLayout(True) - self.SetSizer(sizer_main) - sizer_main.Fit(self) - sizer_main.SetSizeHints(self) - self.Layout() - - -def startApp(): - MainApp = wx.PySimpleApp(0) - wx.InitAllImageHandlers() #you may or may not need this - myFrame = MainFrame(None, -1, "") - - MainApp.SetTopWindow(myFrame) - myFrame.Show() - - MainApp.MainLoop() \ No newline at end of file Deleted: trunk/lib/roreditor/MainFrame_org.py =================================================================== --- trunk/lib/roreditor/MainFrame_org.py 2007-08-08 00:11:50 UTC (rev 160) +++ trunk/lib/roreditor/MainFrame_org.py 2007-08-08 01:34:35 UTC (rev 161) @@ -1,1214 +0,0 @@ -import sys, os, os.path - -from wxogre.OgreManager import * -from ror.RoROgreWindow import * - -from ror.logger import log -from ror.settingsManager import getSettingsManager - -from ror.rorcommon import * -from RoRTerrainOgreWindow import * -from RoRTerrainSelectedObjectOgreWindow import * -from RoRTerrainSelectedObjectTopOgreWindow import * - -import wx -import wx.grid -import wx.html -import wx.aui - -import cStringIO - -ID_OpenTerrain = wx.NewId() - -ID_CreateOgre = wx.NewId() - - -ID_CreateTree = wx.NewId() -ID_CreateGrid = wx.NewId() -ID_CreateText = wx.NewId() -ID_CreateHTML = wx.NewId() -ID_CreateSizeReport = wx.NewId() -ID_GridContent = wx.NewId() -ID_TextContent = wx.NewId() -ID_TreeContent = wx.NewId() -ID_HTMLContent = wx.NewId() -ID_SizeReportContent = wx.NewId() -ID_CreatePerspective = wx.NewId() -ID_CopyPerspective = wx.NewId() - -ID_TransparentHint = wx.NewId() -ID_VenetianBlindsHint = wx.NewId() -ID_RectangleHint = wx.NewId() -ID_NoHint = wx.NewId() -ID_HintFade = wx.NewId() -ID_AllowFloating = wx.NewId() -ID_NoVenetianFade = wx.NewId() -ID_TransparentDrag = wx.NewId() -ID_AllowActivePane = wx.NewId() -ID_NoGradient = wx.NewId() -ID_VerticalGradient = wx.NewId() -ID_HorizontalGradient = wx.NewId() - -ID_Settings = wx.NewId() -ID_About = wx.NewId() -ID_FirstPerspective = ID_CreatePerspective+1000 - -DATADIR = "data" -TRUCKDIR = os.path.join(DATADIR, "trucks") -TERRAINDIR = os.path.join(DATADIR, "terrains") -OBJECTDIR = os.path.join(DATADIR, "objects") - -#---------------------------------------------------------------------- -def GetMondrianData(): - return \ -'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\x00\x00 \x08\x06\x00\ -\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\x00\x00qID\ -ATX\x85\xed\xd6;\n\x800\x10E\xd1{\xc5\x8d\xb9r\x97\x16\x0b\xad$\x8a\x82:\x16\ -o\xda\x84pB2\x1f\x81Fa\x8c\x9c\x08\x04Z{\xcf\xa72\xbcv\xfa\xc5\x08 \x80r\x80\ -\xfc\xa2\x0e\x1c\xe4\xba\xfaX\x1d\xd0\xde]S\x07\x02\xd8>\xe1wa-`\x9fQ\xe9\ -\x86\x01\x04\x10\x00\\(Dk\x1b-\x04\xdc\x1d\x07\x14\x98;\x0bS\x7f\x7f\xf9\x13\ -\x04\x10@\xf9X\xbe\x00\xc9 \x14K\xc1<={\x00\x00\x00\x00IEND\xaeB`\x82' - - -def GetMondrianBitmap(): - return wx.BitmapFromImage(GetMondrianImage()) - - -def GetMondrianImage(): - stream = cStringIO.StringIO(GetMondrianData()) - return wx.ImageFromStream(stream) - - -def GetMondrianIcon(): - icon = wx.EmptyIcon() - icon.CopyFromBitmap(GetMondrianBitmap()) - return icon - - -class MainFrame(wx.Frame): - - def __init__(self, parent, id=-1, title="", pos=wx.DefaultPosition, - size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE | - wx.SUNKEN_BORDER | - wx.CLIP_CHILDREN): - - wx.Frame.__init__(self, parent, id, title, pos, size, style) - - # tell FrameManager to manage this frame - self._mgr = wx.aui.AuiManager() - self._mgr.SetManagedWindow(self) - - self._perspectives = [] - self.n = 0 - self.x = 0 - - self.SetIcon(GetMondrianIcon()) - - # create menu - mb = wx.MenuBar() - - file_menu = wx.Menu() - file_menu.Append(ID_OpenTerrain, "Open Terrain") - file_menu.Append(wx.ID_EXIT, "Exit") - - view_menu = wx.Menu() - view_menu.Append(ID_CreateOgre, "Create OgreWindow") - view_menu.Append(ID_CreateText, "Create Text Control") - view_menu.Append(ID_CreateHTML, "Create HTML Control") - view_menu.Append(ID_CreateTree, "Create Tree") - view_menu.Append(ID_CreateGrid, "Create Grid") - view_menu.Append(ID_CreateSizeReport, "Create Size Reporter") - view_menu.AppendSeparator() - view_menu.Append(ID_GridContent, "Use a Grid for the Content Pane") - view_menu.Append(ID_TextContent, "Use a Text Control for the Content Pane") - view_menu.Append(ID_HTMLContent, "Use an HTML Control for the Content Pane") - view_menu.Append(ID_TreeContent, "Use a Tree Control for the Content Pane") - view_menu.Append(ID_SizeReportContent, "Use a Size Reporter for the Content Pane") - - options_menu = wx.Menu() - options_menu.AppendRadioItem(ID_TransparentHint, "Transparent Hint") - options_menu.AppendRadioItem(ID_VenetianBlindsHint, "Venetian Blinds Hint") - options_menu.AppendRadioItem(ID_RectangleHint, "Rectangle Hint") - options_menu.AppendRadioItem(ID_NoHint, "No Hint") - options_menu.AppendSeparator(); - options_menu.AppendCheckItem(ID_HintFade, "Hint Fade-in") - options_menu.AppendCheckItem(ID_AllowFloating, "Allow Floating") - options_menu.AppendCheckItem(ID_NoVenetianFade, "Disable Venetian Blinds Hint Fade-in") - options_menu.AppendCheckItem(ID_TransparentDrag, "Transparent Drag") - options_menu.AppendCheckItem(ID_AllowActivePane, "Allow Active Pane") - options_menu.AppendSeparator(); - options_menu.AppendRadioItem(ID_NoGradient, "No Caption Gradient") - options_menu.AppendRadioItem(ID_VerticalGradient, "Vertical Caption Gradient") - options_menu.AppendRadioItem(ID_HorizontalGradient, "Horizontal Caption Gradient") - options_menu.AppendSeparator(); - options_menu.Append(ID_Settings, "Settings Pane") - - self._perspectives_menu = wx.Menu() - self._perspectives_menu.Append(ID_CreatePerspective, "Create Perspective") - self._perspectives_menu.Append(ID_CopyPerspective, "Copy Perspective Data To Clipboard") - self._perspectives_menu.AppendSeparator() - self._perspectives_menu.Append(ID_FirstPerspective+0, "Default Startup") - self._perspectives_menu.Append(ID_FirstPerspective+1, "All Panes") - self._perspectives_menu.Append(ID_FirstPerspective+2, "Vertical Toolbar") - - help_menu = wx.Menu() - help_menu.Append(ID_About, "About...") - - mb.Append(file_menu, "File") - mb.Append(view_menu, "View") - mb.Append(self._perspectives_menu, "Perspectives") - mb.Append(options_menu, "Options") - mb.Append(help_menu, "Help") - - self.SetMenuBar(mb) - - self.statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP) - self.statusbar.SetStatusWidths([-2, -3]) - self.statusbar.SetStatusText("Ready", 0) - self.statusbar.SetStatusText("Welcome To wxPython!", 1) - - # min size for the frame itself isn't completely done. - # see the end up FrameManager::Update() for the test - # code. For now, just hard code a frame minimum size - self.SetMinSize(wx.Size(400, 300)) - - # create some toolbars - tb1 = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, - wx.TB_FLAT | wx.TB_NODIVIDER) - tb1.SetToolBitmapSize(wx.Size(48,48)) - tb1.AddLabelTool(101, "Test", wx.ArtProvider_GetBitmap(wx.ART_ERROR)) - tb1.AddSeparator() - tb1.AddLabelTool(102, "Test", wx.ArtProvider_GetBitmap(wx.ART_QUESTION)) - tb1.AddLabelTool(103, "Test", wx.ArtProvider_GetBitmap(wx.ART_INFORMATION)) - tb1.AddLabelTool(103, "Test", wx.ArtProvider_GetBitmap(wx.ART_WARNING)) - tb1.AddLabelTool(103, "Test", wx.ArtProvider_GetBitmap(wx.ART_MISSING_IMAGE)) - tb1.Realize() - - tb2 = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, - wx.TB_FLAT | wx.TB_NODIVIDER) - tb2.SetToolBitmapSize(wx.Size(16,16)) - tb2_bmp1 = wx.ArtProvider_GetBitmap(wx.ART_QUESTION, wx.ART_OTHER, wx.Size(16, 16)) - tb2.AddLabelTool(101, "Test", tb2_bmp1) - tb2.AddLabelTool(101, "Test", tb2_bmp1) - tb2.AddLabelTool(101, "Test", tb2_bmp1) - tb2.AddLabelTool(101, "Test", tb2_bmp1) - tb2.AddSeparator() - tb2.AddLabelTool(101, "Test", tb2_bmp1) - tb2.AddLabelTool(101, "Test", tb2_bmp1) - tb2.AddSeparator() - tb2.AddLabelTool(101, "Test", tb2_bmp1) - tb2.AddLabelTool(101, "Test", tb2_bmp1) - tb2.AddLabelTool(101, "Test", tb2_bmp1) - tb2.AddLabelTool(101, "Test", tb2_bmp1) - tb2.Realize() - - tb3 = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, - wx.TB_FLAT | wx.TB_NODIVIDER) - tb3.SetToolBitmapSize(wx.Size(16,16)) - tb3_bmp1 = wx.ArtProvider_GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, wx.Size(16, 16)) - tb3.AddLabelTool(101, "Test", tb3_bmp1) - tb3.AddLabelTool(101, "Test", tb3_bmp1) - tb3.AddLabelTool(101, "Test", tb3_bmp1) - tb3.AddLabelTool(101, "Test", tb3_bmp1) - tb3.AddSeparator() - tb3.AddLabelTool(101, "Test", tb3_bmp1) - tb3.AddLabelTool(101, "Test", tb3_bmp1) - tb3.Realize() - - tb4 = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER | wx.TB_HORZ_TEXT) - tb4.SetToolBitmapSize(wx.Size(16,16)) - tb4_bmp1 = wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16)) - tb4.AddLabelTool(101, "Item 1", tb4_bmp1) - tb4.AddLabelTool(101, "Item 2", tb4_bmp1) - tb4.AddLabelTool(101, "Item 3", tb4_bmp1) - tb4.AddLabelTool(101, "Item 4", tb4_bmp1) - tb4.AddSeparator() - tb4.AddLabelTool(101, "Item 5", tb4_bmp1) - tb4.AddLabelTool(101, "Item 6", tb4_bmp1) - tb4.AddLabelTool(101, "Item 7", tb4_bmp1) - tb4.AddLabelTool(101, "Item 8", tb4_bmp1) - tb4.Realize() - - tb5 = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, - wx.TB_FLAT | wx.TB_NODIVIDER | wx.TB_VERTICAL) - tb5.SetToolBitmapSize(wx.Size(48, 48)) - tb5.AddLabelTool(101, "Test", wx.ArtProvider_GetBitmap(wx.ART_ERROR)) - tb5.AddSeparator() - tb5.AddLabelTool(102, "Test", wx.ArtProvider_GetBitmap(wx.ART_QUESTION)) - tb5.AddLabelTool(103, "Test", wx.ArtProvider_GetBitmap(wx.ART_INFORMATION)) - tb5.AddLabelTool(103, "Test", wx.ArtProvider_GetBitmap(wx.ART_WARNING)) - tb5.AddLabelTool(103, "Test", wx.ArtProvider_GetBitmap(wx.ART_MISSING_IMAGE)) - tb5.Realize() - - # add a bunch of panes - self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo(). - Name("test1").Caption("Pane Caption").Top(). - CloseButton(True).MaximizeButton(True)) - - self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo(). - Name("test2").Caption("Client Size Reporter"). - Bottom().Position(1).CloseButton(True).MaximizeButton(True)) - - self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo(). - Name("test3").Caption("Client Size Reporter"). - Bottom().CloseButton(True).MaximizeButton(True)) - - self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo(). - Name("test4").Caption("Pane Caption"). - Left().CloseButton(True).MaximizeButton(True)) - - self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo(). - Name("test5").Caption("Pane Caption"). - Right().CloseButton(True).MaximizeButton(True)) - - self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo(). - Name("test6").Caption("Client Size Reporter"). - Right().Row(1).CloseButton(True).MaximizeButton(True)) - - self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo(). - Name("test7").Caption("Client Size Reporter"). - Left().Layer(1).CloseButton(True).MaximizeButton(True)) - - self._mgr.AddPane(self.CreateTreeCtrl(), wx.aui.AuiPaneInfo(). - Name("test8").Caption("Tree Pane"). - Left().Layer(1).Position(1).CloseButton(True).MaximizeButton(True)) - - self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo(). - Name("test9").Caption("Min Size 200x100"). - BestSize(wx.Size(200,100)).MinSize(wx.Size(200,100)). - Bottom().Layer(1).CloseButton(True).MaximizeButton(True)) - - self._mgr.AddPane(self.CreateTextCtrl(), wx.aui.AuiPaneInfo(). - Name("test10").Caption("Text Pane"). - Bottom().Layer(1).Position(1).CloseButton(True).MaximizeButton(True)) - - self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo(). - Name("test11").Caption("Fixed Pane"). - Bottom().Layer(1).Position(2).Fixed().CloseButton(True).MaximizeButton(True)) - - self._mgr.AddPane(SettingsPanel(self, self), wx.aui.AuiPaneInfo(). - Name("settings").Caption("Dock Manager Settings"). - Dockable(False).Float().Hide().CloseButton(True).MaximizeButton(True)) - - # create some center panes - self._mgr.AddPane(self.CreateTreeCtrl(), wx.aui.AuiPaneInfo().Name("tree_content"). - CenterPane().Hide()) - - self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo().Name("sizereport_content"). - CenterPane().Hide()) - - self._mgr.AddPane(self.CreateTextCtrl(), wx.aui.AuiPaneInfo().Name("text_content"). - CenterPane().Hide()) - - self._mgr.AddPane(self.CreateHTMLCtrl(), wx.aui.AuiPaneInfo().Name("grid_content"). - CenterPane().Hide()) - - #Timer creation (for rendering) - self.ogreTimer = wx.Timer() - self.ogreTimer.SetOwner(self) - self.Bind(wx.EVT_TIMER, self.onUpdateRender, self.ogreTimer) - self.ogreTimer.Start(25) - - self.rordir = getSettingsManager().getSetting("RigsOfRods", "BasePath") - self.ogrewin = RoRTerrainOgreWindow(self, wx.ID_ANY, rordir=self.rordir) - self._mgr.AddPane(self.ogrewin, wx.aui.AuiPaneInfo().Name("html_content"). - CenterPane()) - - # add the toolbars to the manager - - self._mgr.AddPane(tb1, wx.aui.AuiPaneInfo(). - Name("tb1").Caption("Big Toolbar"). - ToolbarPane().Top(). - LeftDockable(False).RightDockable(False)) - - self._mgr.AddPane(tb2, wx.aui.AuiPaneInfo(). - Name("tb2").Caption("Toolbar 2"). - ToolbarPane().Top().Row(1). - LeftDockable(False).RightDockable(False)) - - self._mgr.AddPane(tb3, wx.aui.AuiPaneInfo(). - Name("tb3").Caption("Toolbar 3"). - ToolbarPane().Top().Row(1).Position(1). - LeftDockable(False).RightDockable(False)) - - self._mgr.AddPane(tb4, wx.aui.AuiPaneInfo(). - Name("tb4").Caption("Sample Bookmark Toolbar"). - ToolbarPane().Top().Row(2). - LeftDockable(False).RightDockable(False)) - - self._mgr.AddPane(tb5, wx.aui.AuiPaneInfo(). - Name("tbvert").Caption("Sample Vertical Toolbar"). - ToolbarPane().Left().GripperTop(). - TopDockable(False).BottomDockable(False)) - - self._mgr.AddPane(wx.Button(self, -1, "Test Button"), - wx.aui.AuiPaneInfo().Name("tb5"). - ToolbarPane().Top().Row(2).Position(1). - LeftDockable(False).RightDockable(False)) - - # make some default perspectives - - self._mgr.GetPane("tbvert").Hide() - - perspective_all = self._mgr.SavePerspective() - - all_panes = self._mgr.GetAllPanes() - - for ii in xrange(len(all_panes)): - if not all_panes[ii].IsToolbar(): - all_panes[ii].Hide() - - self._mgr.GetPane("tb1").Hide() - self._mgr.GetPane("tb5").Hide() - self._mgr.GetPane("test8").Show().Left().Layer(0).Row(0).Position(0) - self._mgr.GetPane("test10").Show().Bottom().Layer(0).Row(0).Position(0) - self._mgr.GetPane("html_content").Show() - - perspective_default = self._mgr.SavePerspective() - - for ii in xrange(len(all_panes)): - if not all_panes[ii].IsToolbar(): - all_panes[ii].Hide() - - self._mgr.GetPane("tb1").Hide() - self._mgr.GetPane("tb5").Hide() - self._mgr.GetPane("tbvert").Show() - self._mgr.GetPane("grid_content").Show() - self._mgr.GetPane("test8").Show().Left().Layer(0).Row(0).Position(0) - self._mgr.GetPane("test10").Show().Bottom().Layer(0).Row(0).Position(0) - self._mgr.GetPane("html_content").Show() - - perspective_vert = self._mgr.SavePerspective() - - self._perspectives.append(perspective_default) - self._perspectives.append(perspective_all) - self._perspectives.append(perspective_vert) - - self._mgr.GetPane("tbvert").Hide() - self._mgr.GetPane("grid_content").Hide() - - # "commit" all changes made to FrameManager - self._mgr.Update() - - self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) - self.Bind(wx.EVT_SIZE, self.OnSize) - self.Bind(wx.EVT_CLOSE, self.OnClose) - - # Show How To Use The Closing Panes Event - self.Bind(wx.aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose) - - - self.Bind(wx.EVT_MENU, self.OnOpenTerrain, id=ID_OpenTerrain) - - self.Bind(wx.EVT_MENU, self.OnCreateOgre, id=ID_CreateOgre) - - self.Bind(wx.EVT_MENU, self.OnCreateTree, id=ID_CreateTree) - self.Bind(wx.EVT_MENU, self.OnCreateGrid, id=ID_CreateGrid) - self.Bind(wx.EVT_MENU, self.OnCreateText, id=ID_CreateText) - self.Bind(wx.EVT_MENU, self.OnCreateHTML, id=ID_CreateHTML) - self.Bind(wx.EVT_MENU, self.OnCreateSizeReport, id=ID_CreateSizeReport) - self.Bind(wx.EVT_MENU, self.OnCreatePerspective, id=ID_CreatePerspective) - self.Bind(wx.EVT_MENU, self.OnCopyPerspective, id=ID_CopyPerspective) - - self.Bind(wx.EVT_MENU, self.OnManagerFlag, id=ID_AllowFloating) - self.Bind(wx.EVT_MENU, self.OnManagerFlag, id=ID_TransparentHint) - self.Bind(wx.EVT_MENU, self.OnManagerFlag, id=ID_VenetianBlindsHint) - self.Bind(wx.EVT_MENU, self.OnManagerFlag, id=ID_RectangleHint) - self.Bind(wx.EVT_MENU, self.OnManagerFlag, id=ID_NoHint) - self.Bind(wx.EVT_MENU, self.OnManagerFlag, id=ID_HintFade) - self.Bind(wx.EVT_MENU, self.OnManagerFlag, id=ID_NoVenetianFade) - self.Bind(wx.EVT_MENU, self.OnManagerFlag, id=ID_TransparentDrag) - self.Bind(wx.EVT_MENU, self.OnManagerFlag, id=ID_AllowActivePane) - - self.Bind(wx.EVT_MENU, self.OnGradient, id=ID_NoGradient) - self.Bind(wx.EVT_MENU, self.OnGradient, id=ID_VerticalGradient) - self.Bind(wx.EVT_MENU, self.OnGradient, id=ID_HorizontalGradient) - self.Bind(wx.EVT_MENU, self.OnSettings, id=ID_Settings) - self.Bind(wx.EVT_MENU, self.OnChangeContentPane, id=ID_GridContent) - self.Bind(wx.EVT_MENU, self.OnChangeContentPane, id=ID_TreeContent) - self.Bind(wx.EVT_MENU, self.OnChangeContentPane, id=ID_TextContent) - self.Bind(wx.EVT_MENU, self.OnChangeContentPane, id=ID_SizeReportContent) - self.Bind(wx.EVT_MENU, self.OnChangeContentPane, id=ID_HTMLContent) - self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT) - self.Bind(wx.EVT_MENU, self.OnAbout, id=ID_About) - - self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=ID_TransparentHint) - self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=ID_VenetianBlindsHint) - self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=ID_RectangleHint) - self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=ID_NoHint) - self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=ID_HintFade) - self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=ID_AllowFloating) - self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=ID_NoVenetianFade) - self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=ID_TransparentDrag) - self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=ID_AllowActivePane) - self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=ID_NoGradient) - self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=ID_VerticalGradient) - self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, id=ID_HorizontalGradient) - - - self.Bind(wx.EVT_MENU_RANGE, self.OnRestorePerspective, id=ID_FirstPerspective, - id2=ID_FirstPerspective+1000) - - def onUpdateRender(self, event=None): - getOgreManager().RenderAll() - pass - - def OnOpenTerrain(self, event=None): - default = "" - if self.rordir: - default = os.path.join(self.rordir, TERRAINDIR) - dialog = wx.FileDialog(self, "Open Terrain", default, "", "Terrain Files (*.terrn)|*.terrn", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) - res = dialog.ShowModal() - if res == wx.ID_OK: - filename = dialog.GetPath() - self.ogrewin.LoadTerrain(filename) - - - def OnPaneClose(self, event): - - caption = event.GetPane().caption - - if caption in ["Tree Pane", "Dock Manager Settings", "Fixed Pane"]: - msg = "Are You Sure You Want To Close This Pane?" - dlg = wx.MessageDialog(self, msg, "AUI Question", - wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) - - if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]: - event.Veto() - dlg.Destroy() - - - def OnClose(self, event): - self._mgr.UnInit() - del self._mgr - self.Destroy() - - - def OnExit(self, event): - self.Close() - - def OnAbout(self, event): - - msg = "wx.aui Demo\n" + \ - "An advanced window management library for wxWidgets\n" + \ - "(c) Copyright 2005-2006, Kirix Corporation" - dlg = wx.MessageDialog(self, msg, "About wx.aui Demo", - wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - - - def GetDockArt(self): - - return self._mgr.GetArtProvider() - - - def DoUpdate(self): - - self._mgr.Update() - - - def OnEraseBackground(self, event): - - event.Skip() - - - def OnSize(self, event): - - event.Skip() - - - def OnSettings(self, event): - - # show the settings pane, and float it - floating_pane = self._mgr.GetPane("settings").Float().Show() - - if floating_pane.floating_pos == wx.DefaultPosition: - floating_pane.FloatingPosition(self.GetStartPosition()) - - self._mgr.Update() - - - def OnGradient(self, event): - - gradient = 0 - - if event.GetId() == ID_NoGradient: - gradient = wx.aui.AUI_GRADIENT_NONE - elif event.GetId() == ID_VerticalGradient: - gradient = wx.aui.AUI_GRADIENT_VERTICAL - elif event.GetId() == ID_HorizontalGradient: - gradient = wx.aui.AUI_GRADIENT_HORIZONTAL - - self._mgr.GetArtProvider().SetMetric(wx.aui.AUI_DOCKART_GRADIENT_TYPE, gradient) - self._mgr.Update() - - - def OnManagerFlag(self, event): - - flag = 0 - eid = event.GetId() - - if eid in [ ID_TransparentHint, ID_VenetianBlindsHint, ID_RectangleHint, ID_NoHint ]: - flags = self._mgr.GetFlags() - flags &= ~wx.aui.AUI_MGR_TRANSPARENT_HINT - flags &= ~wx.aui.AUI_MGR_VENETIAN_BLINDS_HINT - flags &= ~wx.aui.AUI_MGR_RECTANGLE_HINT - self._mgr.SetFlags(flags) - - if eid == ID_AllowFloating: - flag = wx.aui.AUI_MGR_ALLOW_FLOATING - elif eid == ID_TransparentDrag: - flag = wx.aui.AUI_MGR_TRANSPARENT_DRAG - elif eid == ID_HintFade: - flag = wx.aui.AUI_MGR_HINT_FADE - elif eid == ID_NoVenetianFade: - flag = wx.aui.AUI_MGR_NO_VENETIAN_BLINDS_FADE - elif eid == ID_AllowActivePane: - flag = wx.aui.AUI_MGR_ALLOW_ACTIVE_PANE - elif eid == ID_TransparentHint: - flag = wx.aui.AUI_MGR_TRANSPARENT_HINT - elif eid == ID_VenetianBlindsHint: - flag = wx.aui.AUI_MGR_VENETIAN_BLINDS_HINT - elif eid == ID_RectangleHint: - flag = wx.aui.AUI_MGR_RECTANGLE_HINT - - self._mgr.SetFlags(self._mgr.GetFlags() ^ flag) - - - def OnUpdateUI(self, event): - - flags = self._mgr.GetFlags() - eid = event.GetId() - - if eid == ID_NoGradient: - event.Check(self._mgr.GetArtProvider().GetMetric(wx.aui.AUI_DOCKART_GRADIENT_TYPE) == wx.aui.AUI_GRADIENT_NONE) - - elif eid == ID_VerticalGradient: - event.Check(self._mgr.GetArtProvider().GetMetric(wx.aui.AUI_DOCKART_GRADIENT_TYPE) == wx.aui.AUI_GRADIENT_VERTICAL) - - elif eid == ID_HorizontalGradient: - event.Check(self._mgr.GetArtProvider().GetMetric(wx.aui.AUI_DOCKART_GRADIENT_TYPE) == wx.aui.AUI_GRADIENT_HORIZONTAL) - - elif eid == ID_AllowFloating: - event.Check((flags & wx.aui.AUI_MGR_ALLOW_FLOATING) != 0) - - elif eid == ID_TransparentDrag: - event.Check((flags & wx.aui.AUI_MGR_TRANSPARENT_DRAG) != 0) - - elif eid == ID_TransparentHint: - event.Check((flags & wx.aui.AUI_MGR_TRANSPARENT_HINT) != 0) - - elif eid == ID_VenetianBlindsHint: - event.Check((flags & wx.aui.AUI_MGR_VENETIAN_BLINDS_HINT) != 0) - - elif eid == ID_RectangleHint: - event.Check((flags & wx.aui.AUI_MGR_RECTANGLE_HINT) != 0) - - elif eid == ID_NoHint: - event.Check(((wx.aui.AUI_MGR_TRANSPARENT_HINT | - wx.aui.AUI_MGR_VENETIAN_BLINDS_HINT | - wx.aui.AUI_MGR_RECTANGLE_HINT) & flags) == 0) - - elif eid == ID_HintFade: - event.Check((flags & wx.aui.AUI_MGR_HINT_FADE) != 0); - - elif eid == ID_NoVenetianFade: - event.Check((flags & wx.aui.AUI_MGR_NO_VENETIAN_BLINDS_FADE) != 0); - - - - - def OnCreatePerspective(self, event): - - dlg = wx.TextEntryDialog(self, "Enter a name for the new perspective:", "AUI Test") - - dlg.SetValue(("Perspective %d")%(len(self._perspectives)+1)) - if dlg.ShowModal() != wx.ID_OK: - return - - if len(self._perspectives) == 0: - self._perspectives_menu.AppendSeparator() - - self._perspectives_menu.Append(ID_FirstPerspective + len(self._perspectives), dlg.GetValue()) - self._perspectives.append(self._mgr.SavePerspective()) - - - def OnCopyPerspective(self, event): - - s = self._mgr.SavePerspective() - - if wx.TheClipboard.Open(): - - wx.TheClipboard.SetData(wx.TextDataObject(s)) - wx.TheClipboard.Close() - - def OnRestorePerspective(self, event): - - self._mgr.LoadPerspective(self._perspectives[event.GetId() - ID_FirstPerspective]) - - - def GetStartPosition(self): - - self.x = self.x + 20 - x = self.x - pt = self.ClientToScreen(wx.Point(0, 0)) - - return wx.Point(pt.x + x, pt.y + x) - - - def OnCreateTree(self, event): - self._mgr.AddPane(self.CreateTreeCtrl(), wx.aui.AuiPaneInfo(). - Caption("Tree Control"). - Float().FloatingPosition(self.GetStartPosition()). - FloatingSize(wx.Size(150, 300)).CloseButton(True).MaximizeButton(True)) - self._mgr.Update() - - - def OnCreateGrid(self, event): - self._mgr.AddPane(self.CreateGrid(), wx.aui.AuiPaneInfo(). - Caption("Grid"). - Float().FloatingPosition(self.GetStartPosition()). - FloatingSize(wx.Size(300, 200)).CloseButton(True).MaximizeButton(True)) - self._mgr.Update() - - - def OnCreateHTML(self, event): - self._mgr.AddPane(self.CreateHTMLCtrl(), wx.aui.AuiPaneInfo(). - Caption("HTML Content"). - Float().FloatingPosition(self.GetStartPosition()). - FloatingSize(wx.Size(300, 200)).CloseButton(True).MaximizeButton(True)) - self._mgr.Update() - - - def OnCreateText(self, event): - self._mgr.AddPane(self.CreateTextCtrl(), wx.aui.AuiPaneInfo(). - Caption("Text Control"). - Float().FloatingPosition(self.GetStartPosition()). - CloseButton(True).MaximizeButton(True)) - self._mgr.Update() - - - def OnCreateSizeReport(self, event): - self._mgr.AddPane(self.CreateSizeReportCtrl(), wx.aui.AuiPaneInfo(). - Caption("Client Size Reporter"). - Float().FloatingPosition(self.GetStartPosition()). - CloseButton(True).MaximizeButton(True)) - self._mgr.Update() - - - def OnChangeContentPane(self, event): - - self._mgr.GetPane("grid_content").Show(event.GetId() == ID_GridContent) - self._mgr.GetPane("text_content").Show(event.GetId() == ID_TextContent) - self._mgr.GetPane("tree_content").Show(event.GetId() == ID_TreeContent) - self._mgr.GetPane("sizereport_content").Show(event.GetId() == ID_SizeReportContent) - self._mgr.GetPane("html_content").Show(event.GetId() == ID_HTMLContent) - self._mgr.Update() - - def OnCreateOgre(self, event): - self._mgr.AddPane(self.CreateOgreCtrl(), wx.aui.AuiPaneInfo(). - Caption("Ogre Window"). - Float().FloatingPosition(self.GetStartPosition()). - CloseButton(True).MaximizeButton(True)) - self._mgr.Update() - - - def CreateOgreCtrl(self): - return RoRTerrainOgreWindow(self, wx.ID_ANY, scenemanager=self.ogrewin.sceneManager) - - def CreateTextCtrl(self): - - text = ("This is text box %d")%(self.n + 1) - - return wx.TextCtrl(self,-1, text, wx.Point(0, 0), wx.Size(150, 90), - wx.NO_BORDER | wx.TE_MULTILINE) - - - - def CreateGrid(self): - - grid = wx.grid.Grid(self, -1, wx.Point(0, 0), wx.Size(150, 250), - wx.NO_BORDER | wx.WANTS_CHARS) - - grid.CreateGrid(50, 20) - - return grid - - - def CreateTreeCtrl(self): - - tree = wx.TreeCtrl(self, -1, wx.Point(0, 0), wx.Size(160, 250), - wx.TR_DEFAULT_STYLE | wx.NO_BORDER) - - root = tree.AddRoot("AUI Project") - items = [] - - imglist = wx.ImageList(16, 16, True, 2) - imglist.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, wx.Size(16,16))) - imglist.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16,16))) - tree.AssignImageList(imglist) - - items.append(tree.AppendItem(root, "Item 1", 0)) - items.append(tree.AppendItem(root, "Item 2", 0)) - items.append(tree.AppendItem(root, "Item 3", 0)) - items.append(tree.AppendItem(root, "Item 4", 0)) - items.append(tree.AppendItem(root, "Item 5", 0)) - - for ii in xrange(len(items)): - - id = items[ii] - tree.AppendItem(id, "Subitem 1", 1) - tree.AppendItem(id, "Subitem 2", 1) - tree.AppendItem(id, "Subitem 3", 1) - tree.AppendItem(id, "Subitem 4", 1) - tree.AppendItem(id, "Subitem 5", 1) - - tree.Expand(root) - - return tree - - - def CreateSizeReportCtrl(self, width=80, height=80): - - ctrl = SizeReportCtrl(self, -1, wx.DefaultPosition, - wx.Size(width, height), self._mgr) - return ctrl - - - def CreateHTMLCtrl(self): - ctrl = wx.html.HtmlWindow(self, -1, wx.DefaultPosition, wx.Size(400, 300)) - if "gtk2" in wx.PlatformInfo: - ctrl.SetStandardFonts() - ctrl.SetPage(self.GetIntroText()) - return ctrl - - - def GetIntroText(self): - return overview - - -# -- wx.SizeReportCtrl -- -# (a utility control that always reports it's client size) - -class SizeReportCtrl(wx.PyControl): - - def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, - size=wx.DefaultSize, mgr=None): - - wx.PyControl.__init__(self, parent, id, pos, size, wx.NO_BORDER) - - self._mgr = mgr - - self.Bind(wx.EVT_PAINT, self.OnPaint) - self.Bind(wx.EVT_SIZE, self.OnSize) - self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) - - - def OnPaint(self, event): - - dc = wx.PaintDC(self) - - size = self.GetClientSize() - s = ("Size: %d x %d")%(size.x, size.y) - - dc.SetFont(wx.NORMAL_FONT) - w, height = dc.GetTextExtent(s) - height = height + 3 - dc.SetBrush(wx.WHITE_BRUSH) - dc.SetPen(wx.WHITE_PEN) - dc.DrawRectangle(0, 0, size.x, size.y) - dc.SetPen(wx.LIGHT_GREY_PEN) - dc.DrawLine(0, 0, size.x, size.y) - dc.DrawLine(0, size.y, size.x, 0) - dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)) - - if self._mgr: - - pi = self._mgr.GetPane(self) - - s = ("Layer: %d")%pi.dock_layer - w, h = dc.GetTextExtent(s) - dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)+(height*1)) - - s = ("Dock: %d Row: %d")%(pi.dock_direction, pi.dock_row) - w, h = dc.GetTextExtent(s) - dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)+(height*2)) - - s = ("Position: %d")%pi.dock_pos - w, h = dc.GetTextExtent(s) - dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)+(height*3)) - - s = ("Proportion: %d")%pi.dock_proportion - w, h = dc.GetTextExtent(s) - dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)+(height*4)) - - - def OnEraseBackground(self, event): - # intentionally empty - pass - - - def OnSize(self, event): - - self.Refresh() - event.Skip() - - -ID_PaneBorderSize = wx.ID_HIGHEST + 1 -ID_SashSize = ID_PaneBorderSize + 1 -ID_CaptionSize = ID_PaneBorderSize + 2 -ID_BackgroundColor = ID_PaneBorderSize + 3 -ID_SashColor = ID_PaneBorderSize + 4 -ID_InactiveCaptionColor = ID_PaneBorderSize + 5 -ID_InactiveCaptionGradientColor = ID_PaneBorderSize + 6 -ID_InactiveCaptionTextColor = ID_PaneBorderSize + 7 -ID_ActiveCaptionColor = ID_PaneBorderSize + 8 -ID_ActiveCaptionGradientColor = ID_PaneBorderSize + 9 -ID_ActiveCaptionTextColor = ID_PaneBorderSize + 10 -ID_BorderColor = ID_PaneBorderSize + 11 -ID_GripperColor = ID_PaneBorderSize + 12 - -class SettingsPanel(wx.Panel): - - def __init__(self, parent, frame): - - wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, - wx.DefaultSize) - - self._frame = frame - - vert = wx.BoxSizer(wx.VERTICAL) - - s1 = wx.BoxSizer(wx.HORIZONTAL) - self._border_size = wx.SpinCtrl(self, ID_PaneBorderSize, "", wx.DefaultPosition, wx.Size(50,20)) - s1.Add((1, 1), 1, wx.EXPAND) - s1.Add(wx.StaticText(self, -1, "Pane Border Size:")) - s1.Add(self._border_size) - s1.Add((1, 1), 1, wx.EXPAND) - s1.SetItemMinSize(1, (180, 20)) - #vert.Add(s1, 0, wx.EXPAND | wxLEFT | wxBOTTOM, 5) - - s2 = wx.BoxSizer(wx.HORIZONTAL) - self._sash_size = wx.SpinCtrl(self, ID_SashSize, "", wx.DefaultPosition, wx.Size(50,20)) - s2.Add((1, 1), 1, wx.EXPAND) - s2.Add(wx.StaticText(self, -1, "Sash Size:")) - s2.Add(self._sash_size) - s2.Add((1, 1), 1, wx.EXPAND) - s2.SetItemMinSize(1, (180, 20)) - #vert.Add(s2, 0, wx.EXPAND | wxLEFT | wxBOTTOM, 5) - - s3 = wx.BoxSizer(wx.HORIZONTAL) - self._caption_size = wx.SpinCtrl(self, ID_CaptionSize, "", wx.DefaultPosition, wx.Size(50,20)) - s3.Add((1, 1), 1, wx.EXPAND) - s3.Add(wx.StaticText(self, -1, "Caption Size:")) - s3.Add(self._caption_size) - s3.Add((1, 1), 1, wx.EXPAND) - s3.SetItemMinSize(1, (180, 20)) - #vert.Add(s3, 0, wx.EXPAND | wxLEFT | wxBOTTOM, 5) - - #vert.Add(1, 1, 1, wx.EXPAND) - - b = self.CreateColorBitmap(wx.BLACK) - - s4 = wx.BoxSizer(wx.HORIZONTAL) - self._background_color = wx.BitmapButton(self, ID_BackgroundColor, b, wx.DefaultPosition, wx.Size(50,25)) - s4.Add((1, 1), 1, wx.EXPAND) - s4.Add(wx.StaticText(self, -1, "Background Colo... [truncated message content] |
From: <ror...@us...> - 2007-08-21 10:52:48
|
Revision: 165 http://roreditor.svn.sourceforge.net/roreditor/?rev=165&view=rev Author: rorthomas Date: 2007-08-21 03:52:43 -0700 (Tue, 21 Aug 2007) Log Message: ----------- new dir structure Modified Paths: -------------- trunk/lib_windows/ror/starter.py trunk/lib_windows/wxogre/OgreManager.py Added Paths: ----------- trunk/lib_common/ trunk/lib_linux/ trunk/lib_windows/ Removed Paths: ------------- trunk/lib/ Copied: trunk/lib_windows (from rev 164, trunk/lib) Modified: trunk/lib_windows/ror/starter.py =================================================================== --- trunk/lib/ror/starter.py 2007-08-19 11:16:59 UTC (rev 164) +++ trunk/lib_windows/ror/starter.py 2007-08-21 10:52:43 UTC (rev 165) @@ -19,287 +19,289 @@ class ImagePanel(wx.Panel): - """ class Panel1 creates a panel with an image on it, inherits wx.Panel """ - def __init__(self, parent, id, imageFile): - wx.Panel.__init__(self, parent, id) - try: - jpg1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap() - wx.StaticBitmap(self, wx.ID_ANY, jpg1, (0, 0), (jpg1.GetWidth(), jpg1.GetHeight())) - except IOError: - log().error("Image file %s not found" % imageFile) - raise SystemExit + """ class Panel1 creates a panel with an image on it, inherits wx.Panel """ + def __init__(self, parent, id, imageFile): + wx.Panel.__init__(self, parent, id) + try: + jpg1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap() + wx.StaticBitmap(self, wx.ID_ANY, jpg1, (0, 0), (jpg1.GetWidth(), jpg1.GetHeight())) + except IOError: + log().error("Image file %s not found" % imageFile) + raise SystemExit -class SettingsDialog(wx.Frame): - rordir = None - def __init__(self, *args, **kwds): - kwds["style"] = wx.SYSTEM_MENU | wx.CAPTION | wx.CLIP_CHILDREN | wx.CLOSE_BOX - wx.Frame.__init__(self, *args, **kwds) +class SettingsDialog(wx.Frame): + rordir = None + def __init__(self, *args, **kwds): + kwds["style"] = wx.SYSTEM_MENU | wx.CAPTION | wx.CLIP_CHILDREN | wx.CLOSE_BOX + wx.Frame.__init__(self, *args, **kwds) - self.panel = wx.Panel(self, wx.ID_ANY) - - self.image = ImagePanel(self.panel, wx.ID_ANY, SPLASHIMAGE) - - self.lblRoRDir = wx.StaticText(self.panel, wx.ID_ANY, "Please select Rigs of Rods Directory!", size = (20, 40), style = wx.ALIGN_CENTRE | wx.ST_NO_AUTORESIZE) - self.btnSelectRoRDir = wx.Button(self.panel, wx.ID_ANY, "Select RoR Directory") - self.Bind(wx.EVT_BUTTON, self.OnSelectRoRDir, self.btnSelectRoRDir) + self.panel = wx.Panel(self, wx.ID_ANY) - self.btnStartRoR = wx.Button(self.panel, wx.ID_ANY, "Start RoR") - self.Bind(wx.EVT_BUTTON, self.OnStartRoR, self.btnStartRoR) + self.image = ImagePanel(self.panel, wx.ID_ANY, SPLASHIMAGE) - self.cbbRenderEngine = wx.ComboBox(self.panel, wx.ID_ANY, RENDERSYSTEMS[0], style=wx.CB_READONLY, choices=RENDERSYSTEMS) - self.Bind(wx.EVT_COMBOBOX, self.OnSelectRenderer, self.cbbRenderEngine) - - self.btnStartTerrainEditor = wx.Button(self.panel, wx.ID_ANY, "Start Editor") - self.Bind(wx.EVT_BUTTON, self.OnTerrainEditor, self.btnStartTerrainEditor) - - self.btnBugReport = wx.Button(self.panel, wx.ID_ANY, "Report a Bug") - self.Bind(wx.EVT_BUTTON, self.OnBugReport, self.btnBugReport) + self.lblRoRDir = wx.StaticText(self.panel, wx.ID_ANY, "Please select Rigs of Rods Directory!", size = (20, 40), style = wx.ALIGN_CENTRE | wx.ST_NO_AUTORESIZE) + self.btnSelectRoRDir = wx.Button(self.panel, wx.ID_ANY, "Select RoR Directory") + self.Bind(wx.EVT_BUTTON, self.OnSelectRoRDir, self.btnSelectRoRDir) - self.btnUpdate = wx.Button(self.panel, wx.ID_ANY, "Update") - self.Bind(wx.EVT_BUTTON, self.OnUpdate, self.btnUpdate) - - self.btnDepGraph = wx.Button(self.panel, wx.ID_ANY, "Dependency Graph") - self.Bind(wx.EVT_BUTTON, self.OnDepGraph, self.btnDepGraph) + self.btnStartRoR = wx.Button(self.panel, wx.ID_ANY, "Start RoR") + self.Bind(wx.EVT_BUTTON, self.OnStartRoR, self.btnStartRoR) - self.btnModUninstaller = wx.Button(self.panel, wx.ID_ANY, "Mod Uninstaller") - self.Bind(wx.EVT_BUTTON, self.OnModUninstaller, self.btnModUninstaller) + if sys.platform == 'win32': + self.cbbRenderEngine = wx.ComboBox(self.panel, wx.ID_ANY, RENDERSYSTEMS[0], style=wx.CB_READONLY, choices=RENDERSYSTEMS) + self.Bind(wx.EVT_COMBOBOX, self.OnSelectRenderer, self.cbbRenderEngine) - self.btnRepClient = wx.Button(self.panel, wx.ID_ANY, "Repository Client") - self.Bind(wx.EVT_BUTTON, self.OnRepClient, self.btnRepClient) - - self.btnExit = wx.Button(self.panel, wx.ID_ANY, "Exit") - self.Bind(wx.EVT_BUTTON, self.OnExit, self.btnExit) - - self.rordir = getSettingsManager().getSetting("RigsOfRods", "BasePath") - self.checkRoRDir(self.rordir) - - #print self.rordir - self.displayRoRDir() - self.__set_properties() - self.__do_layout() - - self.renderSystem = RENDERSYSTEMS[0] + self.btnStartTerrainEditor = wx.Button(self.panel, wx.ID_ANY, "Start Editor") + self.Bind(wx.EVT_BUTTON, self.OnTerrainEditor, self.btnStartTerrainEditor) - def OnRepClient(self, event=None): - import repomanager - repomanager.main() - - def displayRoRDir(self): - if self.rordir == "": - self.btnStartRoR.Enable(False) - #self.btnStartTruckEditor.Enable(False) - self.btnStartTerrainEditor.Enable(False) - self.btnBugReport.Enable(False) - self.lblRoRDir.SetLabel("Please select Rigs of Rods Directory!") - else: - self.btnStartRoR.Enable(True) - #self.btnStartTruckEditor.Enable(True) - self.btnStartTerrainEditor.Enable(True) - self.btnBugReport.Enable(True) - self.lblRoRDir.SetLabel("Selected Rigs of Rods Directory: " + self.rordir) - - def OnSelectRenderer(self, id=None, func=None): - self.renderSystem = self.cbbRenderEngine.GetCurrentSelection() - self.updateRenderer() + self.btnBugReport = wx.Button(self.panel, wx.ID_ANY, "Report a Bug") + self.Bind(wx.EVT_BUTTON, self.OnBugReport, self.btnBugReport) - def updateRenderer(self): - filename = os.path.join(os.getcwd(), "plugins.cfg") - f=open(filename, 'r') - content = f.readlines() - f.close() - log().info("selected rendersystem: %s" % RENDERSYSTEMS[self.renderSystem]) - for i in range(0, len(content)): - if content[i].find(OPENGLLINE) >= 0: - if self.renderSystem == 0: - content[i] = OPENGLLINE+"\n" - else: - content[i] = "#"+OPENGLLINE+"\n" - elif content[i].find(DIRECTXLINE) >= 0: - if self.renderSystem == 1: - content[i] = DIRECTXLINE+"\n" - else: - content[i] = "#"+DIRECTXLINE+"\n" + self.btnUpdate = wx.Button(self.panel, wx.ID_ANY, "Update") + self.Bind(wx.EVT_BUTTON, self.OnUpdate, self.btnUpdate) - f=open(filename, 'w') - f.writelines(content) - f.close() - - def OnDepGraph(self, event=None): - import ror.depchecker - ror.depchecker.RoRDepChecker(self.rordir, "all", "") - file = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "graphs", "alldependencies.png")) - #print file - if os.path.isfile(file): - dlg = wx.MessageDialog(self, "Graph successfully created:\n"+file, "Info", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - cmd = file - p = subprocess.Popen(cmd, shell = True, stderr = subprocess.PIPE, stdout = subprocess.PIPE) - else: - dlg = wx.MessageDialog(self, "Graph creation failed :(", "Info", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - - def OnModUninstaller(self, event=None): - import modgui - gui = modgui.ModGUI(None, -1, "") - gui.Show() - del gui - - def OnUpdate(self, event=None): - import svngui - gui = svngui.svnUpdate() - del gui + self.btnDepGraph = wx.Button(self.panel, wx.ID_ANY, "Dependency Graph") + self.Bind(wx.EVT_BUTTON, self.OnDepGraph, self.btnDepGraph) - def checkForUpdate(self): - import svn - return svn.checkForUpdate() - + self.btnModUninstaller = wx.Button(self.panel, wx.ID_ANY, "Mod Uninstaller") + self.Bind(wx.EVT_BUTTON, self.OnModUninstaller, self.btnModUninstaller) - def OnStartRoR(self, event=None): - try: - path = os.path.join(self.rordir, "RoR.exe") - log().info("starting RoR: %s" % path) - p = Popen(path, shell = False, cwd = self.rordir) - #sts = os.waitpid(p.pid, 0) - except Exception, e: - log().exception(str(e)) + self.btnRepClient = wx.Button(self.panel, wx.ID_ANY, "Repository Client") + self.Bind(wx.EVT_BUTTON, self.OnRepClient, self.btnRepClient) - # def OnTruckEditor(self, event=None): - # try: - # import rortruckeditor.MainFrame - # self.Close() - # log().info("starting Truckeditor") - # app = rortruckeditor.MainFrame.startApp() - # del app - # except Exception, e: - # log().exception(str(e)) - - def OnBugReport(self, event=None): - try: - if self.checkForUpdate(): - dlg = wx.MessageDialog(self, "Update Available!\nPlease update prior submitting a BugReport!", "Info", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - self.btnBugReport.Enable(False) - return - - log().info("starting bugreporter") - import ror.bugreport - ror.bugreport.showBugReportFrame() - except Exception, e: - log().exception(str(e)) + self.btnExit = wx.Button(self.panel, wx.ID_ANY, "Exit") + self.Bind(wx.EVT_BUTTON, self.OnExit, self.btnExit) - def OnTerrainEditor(self, event=None): - try: - log().info("starting Terraineditor") - self.Close() - app = roreditor.MainFrame.startApp() - del app - #self.Show() - except Exception, e: - log().exception(str(e)) + self.rordir = getSettingsManager().getSetting("RigsOfRods", "BasePath") + self.checkRoRDir(self.rordir) - def checkRoRDir(self, fn): - # withoutspaces = (fn.find(" ") == -1) - # if not withoutspaces: - # dlg = wx.MessageDialog(self, "Your RoR installation directory contains spaces. Rename/move it to a directory with no spaces.\nFor example c:\\ror", "Error", wx.OK | wx.ICON_INFORMATION) - # dlg.ShowModal() - # dlg.Destroy() - # return False - - exists = os.path.isfile(os.path.join(fn,"RoR.exe")) - if not exists: - dlg = wx.MessageDialog(self, "RoR.exe not found in the selected directory!\nPlease select a new directory!", "Error", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - self.rordir = "" - return False - - self.rordir = fn - return True - - def OnSelectRoRDir(self, event=None): - dialog = wx.DirDialog(self, "Choose RoR Directory", "") - res = dialog.ShowModal() - if res == wx.ID_OK: - newpath = dialog.GetPath() - if not self.checkRoRDir(newpath): - return - - # no need to escape here! - #newpath = newpath.replace(" ", "\ ") - self.rordir = newpath - getSettingsManager().setSetting("RigsOfRods", "BasePath", newpath) - self.displayRoRDir() - - def OnExit(self, event=None): - self.Close() - sys.exit(0) + #print self.rordir + self.displayRoRDir() + self.__set_properties() + self.__do_layout() - def __set_properties(self): - #try: - import ror.svn - self.SetTitle("RoR Toolkit r%d" % ror.svn.getRevision()) - #except: - # self.SetTitle("RoR Toolkit") + self.renderSystem = RENDERSYSTEMS[0] - def __do_layout(self): - - sizer_panel = wx.BoxSizer(wx.VERTICAL) - sizer_panel.Add(self.image, 0, wx.EXPAND, 0) - - sizer_a = wx.BoxSizer(wx.HORIZONTAL) - sizer_a.Add(self.lblRoRDir, 1, wx.EXPAND, 0) - sizer_a.Add(self.btnSelectRoRDir, 0, wx.EXPAND, 0) - sizer_panel.Add(sizer_a, 0, wx.EXPAND, 0) - - sizer_b = wx.BoxSizer(wx.HORIZONTAL) - sizer_b.Add(self.btnStartRoR, 0, wx.EXPAND, 0) + def OnRepClient(self, event=None): + import repomanager + repomanager.main() - sizer_c = wx.BoxSizer(wx.VERTICAL) - #sizer_c.Add(self.btnStartTruckEditor, 1, wx.EXPAND, 0) - sizer_c.Add(self.btnStartTerrainEditor, 1, wx.EXPAND, 0) - sizer_b.Add(sizer_c, 1, wx.EXPAND, 0) - - sizer_b.Add(self.cbbRenderEngine, 0, wx.EXPAND, 0) - sizer_panel.Add(sizer_b, 1, wx.EXPAND, 0) + def displayRoRDir(self): + if self.rordir == "": + self.btnStartRoR.Enable(False) + #self.btnStartTruckEditor.Enable(False) + self.btnStartTerrainEditor.Enable(False) + self.btnBugReport.Enable(False) + self.lblRoRDir.SetLabel("Please select Rigs of Rods Directory!") + else: + self.btnStartRoR.Enable(True) + #self.btnStartTruckEditor.Enable(True) + self.btnStartTerrainEditor.Enable(True) + self.btnBugReport.Enable(True) + self.lblRoRDir.SetLabel("Selected Rigs of Rods Directory: " + self.rordir) - sizer_d = wx.BoxSizer(wx.HORIZONTAL) - sizer_d.Add(self.btnBugReport, 1, wx.EXPAND, 0) - sizer_d.Add(self.btnUpdate, 1, wx.EXPAND, 0) - sizer_panel.Add(sizer_d, 0, wx.EXPAND, 0) - - - sizer_e = wx.BoxSizer(wx.HORIZONTAL) - sizer_e.Add(self.btnDepGraph, 1, wx.EXPAND, 0) - sizer_e.Add(self.btnRepClient, 1, wx.EXPAND, 0) - sizer_e.Add(self.btnModUninstaller, 1, wx.EXPAND, 0) - sizer_panel.Add(sizer_e, 0, wx.EXPAND, 0) - - sizer_panel.Add(self.btnExit, 0, wx.EXPAND, 0) - self.panel.SetSizer(sizer_panel) + def OnSelectRenderer(self, id=None, func=None): + self.renderSystem = self.cbbRenderEngine.GetCurrentSelection() + self.updateRenderer() - sizer_main = wx.BoxSizer(wx.VERTICAL) - sizer_main.Add(self.panel, 0, wx.EXPAND, 0) - - self.SetAutoLayout(True) - self.SetSizer(sizer_main) - sizer_main.Fit(self) - sizer_main.SetSizeHints(self) - self.Layout() + def updateRenderer(self): + filename = os.path.join(os.getcwd(), "plugins_windows.cfg") + f=open(filename, 'r') + content = f.readlines() + f.close() + log().info("selected rendersystem: %s" % RENDERSYSTEMS[self.renderSystem]) + for i in range(0, len(content)): + if content[i].find(OPENGLLINE) >= 0: + if self.renderSystem == 0: + content[i] = OPENGLLINE+"\n" + else: + content[i] = "#"+OPENGLLINE+"\n" + elif content[i].find(DIRECTXLINE) >= 0: + if self.renderSystem == 1: + content[i] = DIRECTXLINE+"\n" + else: + content[i] = "#"+DIRECTXLINE+"\n" + f=open(filename, 'w') + f.writelines(content) + f.close() + + def OnDepGraph(self, event=None): + import ror.depchecker + ror.depchecker.RoRDepChecker(self.rordir, "all", "") + file = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "graphs", "alldependencies.png")) + #print file + if os.path.isfile(file): + dlg = wx.MessageDialog(self, "Graph successfully created:\n"+file, "Info", wx.OK | wx.ICON_INFORMATION) + dlg.ShowModal() + dlg.Destroy() + cmd = file + p = subprocess.Popen(cmd, shell = True, stderr = subprocess.PIPE, stdout = subprocess.PIPE) + else: + dlg = wx.MessageDialog(self, "Graph creation failed :(", "Info", wx.OK | wx.ICON_INFORMATION) + dlg.ShowModal() + dlg.Destroy() + + def OnModUninstaller(self, event=None): + import modgui + gui = modgui.ModGUI(None, -1, "") + gui.Show() + del gui + + def OnUpdate(self, event=None): + import svngui + gui = svngui.svnUpdate() + del gui + + def checkForUpdate(self): + import svn + return svn.checkForUpdate() + + + def OnStartRoR(self, event=None): + try: + path = os.path.join(self.rordir, "RoR.exe") + log().info("starting RoR: %s" % path) + p = Popen(path, shell = False, cwd = self.rordir) + #sts = os.waitpid(p.pid, 0) + except Exception, e: + log().exception(str(e)) + + # def OnTruckEditor(self, event=None): + # try: + # import rortruckeditor.MainFrame + # self.Close() + # log().info("starting Truckeditor") + # app = rortruckeditor.MainFrame.startApp() + # del app + # except Exception, e: + # log().exception(str(e)) + + def OnBugReport(self, event=None): + try: + if self.checkForUpdate(): + dlg = wx.MessageDialog(self, "Update Available!\nPlease update prior submitting a BugReport!", "Info", wx.OK | wx.ICON_INFORMATION) + dlg.ShowModal() + dlg.Destroy() + self.btnBugReport.Enable(False) + return + + log().info("starting bugreporter") + import ror.bugreport + ror.bugreport.showBugReportFrame() + except Exception, e: + log().exception(str(e)) + + def OnTerrainEditor(self, event=None): + try: + log().info("starting Terraineditor") + self.Close() + app = roreditor.MainFrame.startApp() + del app + #self.Show() + except Exception, e: + log().exception(str(e)) + + def checkRoRDir(self, fn): + # withoutspaces = (fn.find(" ") == -1) + # if not withoutspaces: + # dlg = wx.MessageDialog(self, "Your RoR installation directory contains spaces. Rename/move it to a directory with no spaces.\nFor example c:\\ror", "Error", wx.OK | wx.ICON_INFORMATION) + # dlg.ShowModal() + # dlg.Destroy() + # return False + + exists = os.path.isfile(os.path.join(fn,"RoR.exe")) + if not exists: + dlg = wx.MessageDialog(self, "RoR.exe not found in the selected directory!\nPlease select a new directory!", "Error", wx.OK | wx.ICON_INFORMATION) + dlg.ShowModal() + dlg.Destroy() + self.rordir = "" + return False + + self.rordir = fn + return True + + def OnSelectRoRDir(self, event=None): + dialog = wx.DirDialog(self, "Choose RoR Directory", "") + res = dialog.ShowModal() + if res == wx.ID_OK: + newpath = dialog.GetPath() + if not self.checkRoRDir(newpath): + return + + # no need to escape here! + #newpath = newpath.replace(" ", "\ ") + self.rordir = newpath + getSettingsManager().setSetting("RigsOfRods", "BasePath", newpath) + self.displayRoRDir() + + def OnExit(self, event=None): + self.Close() + sys.exit(0) + + def __set_properties(self): + #try: + import ror.svn + self.SetTitle("RoR Toolkit r%d" % ror.svn.getRevision()) + #except: + # self.SetTitle("RoR Toolkit") + + def __do_layout(self): + + sizer_panel = wx.BoxSizer(wx.VERTICAL) + sizer_panel.Add(self.image, 0, wx.EXPAND, 0) + + sizer_a = wx.BoxSizer(wx.HORIZONTAL) + sizer_a.Add(self.lblRoRDir, 1, wx.EXPAND, 0) + sizer_a.Add(self.btnSelectRoRDir, 0, wx.EXPAND, 0) + sizer_panel.Add(sizer_a, 0, wx.EXPAND, 0) + + sizer_b = wx.BoxSizer(wx.HORIZONTAL) + sizer_b.Add(self.btnStartRoR, 0, wx.EXPAND, 0) + + sizer_c = wx.BoxSizer(wx.VERTICAL) + #sizer_c.Add(self.btnStartTruckEditor, 1, wx.EXPAND, 0) + sizer_c.Add(self.btnStartTerrainEditor, 1, wx.EXPAND, 0) + sizer_b.Add(sizer_c, 1, wx.EXPAND, 0) + + if sys.platform == 'win32': + sizer_b.Add(self.cbbRenderEngine, 0, wx.EXPAND, 0) + sizer_panel.Add(sizer_b, 1, wx.EXPAND, 0) + + sizer_d = wx.BoxSizer(wx.HORIZONTAL) + sizer_d.Add(self.btnBugReport, 1, wx.EXPAND, 0) + sizer_d.Add(self.btnUpdate, 1, wx.EXPAND, 0) + sizer_panel.Add(sizer_d, 0, wx.EXPAND, 0) + + + sizer_e = wx.BoxSizer(wx.HORIZONTAL) + sizer_e.Add(self.btnDepGraph, 1, wx.EXPAND, 0) + sizer_e.Add(self.btnRepClient, 1, wx.EXPAND, 0) + sizer_e.Add(self.btnModUninstaller, 1, wx.EXPAND, 0) + sizer_panel.Add(sizer_e, 0, wx.EXPAND, 0) + + sizer_panel.Add(self.btnExit, 0, wx.EXPAND, 0) + self.panel.SetSizer(sizer_panel) + + sizer_main = wx.BoxSizer(wx.VERTICAL) + sizer_main.Add(self.panel, 0, wx.EXPAND, 0) + + self.SetAutoLayout(True) + self.SetSizer(sizer_main) + sizer_main.Fit(self) + sizer_main.SetSizeHints(self) + self.Layout() + def startApp(): - MainApp = wx.PySimpleApp() - wx.InitAllImageHandlers() #you may or may not need this - myFrame = SettingsDialog(None, -1, "") + MainApp = wx.PySimpleApp() + wx.InitAllImageHandlers() #you may or may not need this + myFrame = SettingsDialog(None, -1, "") - # add icon to the window - icon = wx.Icon("ror.ico",wx.BITMAP_TYPE_ICO) - myFrame.SetIcon(icon) - MainApp.SetTopWindow(myFrame) - - myFrame.Show() - - MainApp.MainLoop() + # add icon to the window + icon = wx.Icon("ror.ico",wx.BITMAP_TYPE_ICO) + myFrame.SetIcon(icon) + MainApp.SetTopWindow(myFrame) + + myFrame.Show() + + MainApp.MainLoop() Modified: trunk/lib_windows/wxogre/OgreManager.py =================================================================== --- trunk/lib/wxogre/OgreManager.py 2007-08-19 11:16:59 UTC (rev 164) +++ trunk/lib_windows/wxogre/OgreManager.py 2007-08-21 10:52:43 UTC (rev 165) @@ -1,7 +1,7 @@ #Thomas Fischer 31/05/2007, th...@th... import sys import wx -import ogre.renderer.OGRE as ogre +import ogre.renderer.OGRE as ogre from ror.logger import log from ror.ogrelogger import initOgreLogging @@ -11,116 +11,122 @@ # singleton implementation of OgreManager _ogremanager = None def getOgreManager(): - global _ogremanager - if _ogremanager is None: - _ogremanager = OgreManager() - return _ogremanager + global _ogremanager + if _ogremanager is None: + _ogremanager = OgreManager() + return _ogremanager class MyLog(ogre.LogListener): - def __init__(self): - # Creates a C++ log that will try and write to console and file - ogre.LogListener.__init__(self) - - def messageLogged(self, message, level, debug, logName): - print ">>>", message - return True - + def __init__(self): + # Creates a C++ log that will try and write to console and file + ogre.LogListener.__init__(self) + def messageLogged(self, message, level, debug, logName): + print ">>>", message + return True + + class OgreManager(): - renderWindows = {} + renderWindows = {} - def restart(self): - self.ogreRoot.shutdown() - self.init() - - def __init__(self): - self.init() - - def init(self): - #Root creation - self.ogreRoot = ogre.Root(self.getConfigPath('plugins.cfg'), self.getConfigPath('ogre.cfg'), "Ogre.log") - #logMgr = ogre.LogManager() - #currentLog = ogre.LogManager.getSingletonPtr().createLog("ogre.log" ,True, False, False) - #myLog = MyLog() - #currentLog.addListener ( myLog ) - #ogre.LogManager.getSingletonPtr().setDefaultLog(currentLog) + def restart(self): + self.ogreRoot.shutdown() + self.init() - if not self.tryDetectRenderer(): - self.ogreRoot.showConfigDialog() - self.ogreRoot.initialise(False) + def __init__(self): + self.init() - def tryDetectRenderer(self): - for rs in self.ogreRoot.getAvailableRenderers(): - try : - rs.setConfigOption("Full Screen","No") - rs.setConfigOption("Video Mode","800 x 600 @ 32-bit colour") - self.ogreRoot.setRenderSystem(rs) - log().info("successfully autodeteced renderer : %s" % rs.getName()) - return True - except: - log().info("not able to auto-detect renderer! showing ogre config dialog instead") - return False - - def getRoot(self): - return self.ogreRoot - - def getConfigPath(self, filename): - """Return the absolute path to a valid config file.""" - import sys - import os - import os.path - - paths = [os.path.join(os.getcwd(), filename), - os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)] + def init(self): + #Root creation + pluginsfile = 'plugins.cfg' + if sys.platform in ['linux', 'linux2']: + pluginsfile = 'plugins_linux.cfg' + elif sys.platform in ['win32']: + pluginsfile = 'plugins_windows.cfg' + + self.ogreRoot = ogre.Root(self.getConfigPath(pluginsfile), self.getConfigPath('ogre.cfg'), "Ogre.log") + #logMgr = ogre.LogManager() + #currentLog = ogre.LogManager.getSingletonPtr().createLog("ogre.log" ,True, False, False) + #myLog = MyLog() + #currentLog.addListener ( myLog ) + #ogre.LogManager.getSingletonPtr().setDefaultLog(currentLog) - for path in paths: - if os.path.exists(path): - print path - return path + if not self.tryDetectRenderer(): + self.ogreRoot.showConfigDialog() + self.ogreRoot.initialise(False) - sys.stderr.write("\n" - "** Warning: Unable to locate a suitable " + filename + " file.\n" - "** Warning: Please check your ogre installation and copy a\n" - "** Warning: working plugins.cfg file to the current directory.\n\n") - #raise ogre.Exception(0, "can't locate the '%s' file" % filename, "") - - def createRenderWindow(self, wxOgrewin, name, width, height, fullscreen, handle): - renderParameters = ogre.NameValuePairList() - renderParameters['externalWindowHandle'] = str(handle) - # use len to make the names unique! - renderWindow = self.ogreRoot.createRenderWindow(name + str(len(self.renderWindows)), width, height, fullscreen, renderParameters) - #renderWindow.active = True - self.renderWindows[wxOgrewin] = renderWindow - return renderWindow + def tryDetectRenderer(self): + for rs in self.ogreRoot.getAvailableRenderers(): + try : + rs.setConfigOption("Full Screen","No") + rs.setConfigOption("Video Mode","800 x 600 @ 32-bit colour") + self.ogreRoot.setRenderSystem(rs) + log().info("successfully autodeteced renderer : %s" % rs.getName()) + return True + except: + log().info("not able to auto-detect renderer! showing ogre config dialog instead") + return False - def removeRenderWindow(self, wxOgrewin): - print "removing render target" - self.ogreRoot.detachRenderTarget(self.renderWindows[wxOgrewin]) - del self.renderWindows[wxOgrewin] + def getRoot(self): + return self.ogreRoot - def RenderAll(self): - for ogrewin in self.renderWindows.keys(): - try: - ogrewin.OnFrameStarted() - except: - continue - - try: - self.ogreRoot.renderOneFrame() - except ogre.OgreException, e: - print '## EXCEPTION ##' - print str(e) - pass - - for ogrewin in self.renderWindows.keys(): - try: - ogrewin.OnFrameEnded() - except: - continue - - def createSceneManager(self, type): - return self.ogreRoot.createSceneManager(type, "SceneManager" + str(randomID())) + def getConfigPath(self, filename): + """Return the absolute path to a valid config file.""" + import sys + import os + import os.path - def destroySceneManager(self, sm): - return self.ogreRoot.destroySceneManager(sm) - \ No newline at end of file + paths = [os.path.join(os.getcwd(), filename), + os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)] + + for path in paths: + if os.path.exists(path): + print path + return path + + sys.stderr.write("\n" + "** Warning: Unable to locate a suitable " + filename + " file.\n" + "** Warning: Please check your ogre installation and copy a\n" + "** Warning: working plugins.cfg file to the current directory.\n\n") + #raise ogre.Exception(0, "can't locate the '%s' file" % filename, "") + + def createRenderWindow(self, wxOgrewin, name, width, height, fullscreen, handle): + renderParameters = ogre.NameValuePairList() + renderParameters['externalWindowHandle'] = str(handle) + # use len to make the names unique! + renderWindow = self.ogreRoot.createRenderWindow(name + str(len(self.renderWindows)), width, height, fullscreen, renderParameters) + #renderWindow.active = True + self.renderWindows[wxOgrewin] = renderWindow + return renderWindow + + def removeRenderWindow(self, wxOgrewin): + print "removing render target" + self.ogreRoot.detachRenderTarget(self.renderWindows[wxOgrewin]) + del self.renderWindows[wxOgrewin] + + def RenderAll(self): + for ogrewin in self.renderWindows.keys(): + try: + ogrewin.OnFrameStarted() + except: + continue + + try: + self.ogreRoot.renderOneFrame() + except ogre.OgreException, e: + print '## EXCEPTION ##' + print str(e) + pass + + for ogrewin in self.renderWindows.keys(): + try: + ogrewin.OnFrameEnded() + except: + continue + + def createSceneManager(self, type): + return self.ogreRoot.createSceneManager(type, "SceneManager" + str(randomID())) + + def destroySceneManager(self, sm): + return self.ogreRoot.destroySceneManager(sm) + \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-11-27 13:16:18
|
Revision: 189 http://roreditor.svn.sourceforge.net/roreditor/?rev=189&view=rev Author: rorthomas Date: 2007-11-27 05:16:15 -0800 (Tue, 27 Nov 2007) Log Message: ----------- bugfixed updated setup Modified Paths: -------------- trunk/devtools/setup/setup.nsi trunk/lib_common/ror/starter.py Modified: trunk/devtools/setup/setup.nsi =================================================================== --- trunk/devtools/setup/setup.nsi 2007-11-27 12:55:32 UTC (rev 188) +++ trunk/devtools/setup/setup.nsi 2007-11-27 13:16:15 UTC (rev 189) @@ -153,80 +153,80 @@ Abort FunctionEnd -Function InstallDirectX - InitPluginsDir - File /oname=$PLUGINSDIR\dxwebsetup.exe "..\..\tools\3rdparty\dxwebsetup.exe" - Banner::show /NOUNLOAD "Installing lastest DirectX ..." - ExecWait '"$PLUGINSDIR\dxwebsetup.exe /Q"' - Delete $PLUGINSDIR\dxwebsetup.exe - Banner::destroy -FunctionEnd +#Function InstallDirectX +# InitPluginsDir +# File /oname=$PLUGINSDIR\dxwebsetup.exe "..\..\tools\3rdparty\dxwebsetup.exe" +# Banner::show /NOUNLOAD "Installing lastest DirectX ..." +# ExecWait '"$PLUGINSDIR\dxwebsetup.exe /Q"' +# Delete $PLUGINSDIR\dxwebsetup.exe +# Banner::destroy +#FunctionEnd -Function InstallPyWin32 - InitPluginsDir - File /oname=$PLUGINSDIR\pywin32-setup.exe "..\..\tools\3rdparty\pywin32-setup.exe" - Banner::show /NOUNLOAD "Installing Python for Windows ..." - ExecWait '"$PLUGINSDIR\pywin32-setup.exe"' - Delete $PLUGINSDIR\pywin32-setup.exe - Banner::destroy -FunctionEnd +#Function InstallPyWin32 +# InitPluginsDir +# File /oname=$PLUGINSDIR\pywin32-setup.exe "..\..\tools\3rdparty\pywin32-setup.exe" +# Banner::show /NOUNLOAD "Installing Python for Windows ..." +# ExecWait '"$PLUGINSDIR\pywin32-setup.exe"' +# Delete $PLUGINSDIR\pywin32-setup.exe +# Banner::destroy +#FunctionEnd -Function InstallPyParsing - InitPluginsDir - File /oname=$PLUGINSDIR\pyparsing-1.4.6.win32.exe "..\..\tools\3rdparty\pyparsing-1.4.6.win32.exe" - Banner::show /NOUNLOAD "Installing PyParsing Python Module ..." - ExecWait '"$PLUGINSDIR\pyparsing-1.4.6.win32.exe"' - Delete $PLUGINSDIR\pyparsing-1.4.6.win32.exe - Banner::destroy -FunctionEnd +#Function InstallPyParsing +# InitPluginsDir +# File /oname=$PLUGINSDIR\pyparsing-1.4.6.win32.exe "..\..\tools\3rdparty\pyparsing-1.4.6.win32.exe" +# Banner::show /NOUNLOAD "Installing PyParsing Python Module ..." +# ExecWait '"$PLUGINSDIR\pyparsing-1.4.6.win32.exe"' +# Delete $PLUGINSDIR\pyparsing-1.4.6.win32.exe +# Banner::destroy +#FunctionEnd -Function InstallGraphViz - InitPluginsDir - File /oname=$PLUGINSDIR\graphviz-2.12.exe "..\..\tools\3rdparty\graphviz-2.12.exe" - Banner::show /NOUNLOAD "Installing Graphviz for Windows ..." - ExecWait '"$PLUGINSDIR\graphviz-2.12.exe"' - Delete $PLUGINSDIR\graphviz-2.12.exe - Banner::destroy -FunctionEnd +#Function InstallGraphViz +# InitPluginsDir +# File /oname=$PLUGINSDIR\graphviz-2.12.exe "..\..\tools\3rdparty\graphviz-2.12.exe" +# Banner::show /NOUNLOAD "Installing Graphviz for Windows ..." +# ExecWait '"$PLUGINSDIR\graphviz-2.12.exe"' +# Delete $PLUGINSDIR\graphviz-2.12.exe +# Banner::destroy +#FunctionEnd -Function ChangeRoRRepoReg - Banner::show /NOUNLOAD "Updating RoR Repository Protocol Extensions ..." - WriteRegStr HKCR "RoRRepo" "" "URL:RoRRepo Protocol" - WriteRegStr HKCR "RoRRepo" "URL Protocol" "" - WriteRegStr HKCR "RoRRepo\shell" "" "" - WriteRegStr HKCR "RoRRepo\shell\open" "" "" - ReadEnvStr $0 SYSTEMDRIVE - WriteRegStr HKCR 'RoRRepo\shell\open\command' '' '"$0\python25\python.exe" "$INSTDIR\tools\modtool.py" "installrepo" "%1"' - Banner::destroy -FunctionEnd +#Function ChangeRoRRepoReg +# Banner::show /NOUNLOAD "Updating RoR Repository Protocol Extensions ..." +# WriteRegStr HKCR "RoRRepo" "" "URL:RoRRepo Protocol" +# WriteRegStr HKCR "RoRRepo" "URL Protocol" "" +# WriteRegStr HKCR "RoRRepo\shell" "" "" +# WriteRegStr HKCR "RoRRepo\shell\open" "" "" +# ReadEnvStr $0 SYSTEMDRIVE +# WriteRegStr HKCR 'RoRRepo\shell\open\command' '' '"$0\python25\python.exe" "$INSTDIR\tools\modtool.py" "installrepo" "%1"' +# Banner::destroy +#FunctionEnd -Function .onInit - InitPluginsDir - File /oname=$PLUGINSDIR\splash.bmp "splash.bmp" - advsplash::show 1000 1300 600 -1 $PLUGINSDIR\splash - Pop $0 - Delete $PLUGINSDIR\splash.bmp - !insertmacro MUI_LANGDLL_DISPLAY -FunctionEnd +#Function .onInit +# InitPluginsDir +# File /oname=$PLUGINSDIR\splash.bmp "splash.bmp" +# advsplash::show 1000 1300 600 -1 $PLUGINSDIR\splash +# Pop $0 +# Delete $PLUGINSDIR\splash.bmp +# !insertmacro MUI_LANGDLL_DISPLAY +#FunctionEnd Section "-Install Python" SEC01 SectionIn 1 2 RO Call CheckForPython SectionEnd -Section "Required Tools" SEC02 - SectionIn 1 2 RO - Call InstallDirectX -SectionEnd +#Section "Required Tools" SEC02 +# SectionIn 1 2 RO +# Call InstallDirectX +#SectionEnd -Section /o "Optional Tools" SEC03 - AddSize 20000 - SectionIn 1 - Call InstallPyWin32 - Call InstallPyParsing - Call InstallGraphViz -SectionEnd +#Section /o "Optional Tools" SEC03 +# AddSize 20000 +# SectionIn 1 +# Call InstallPyWin32 +# Call InstallPyParsing +# Call InstallGraphViz +#SectionEnd Section "!RoR Toolkit" SEC04 SectionIn 1 2 RO @@ -256,13 +256,11 @@ CreateDirectory "$SMPROGRAMS\RoRToolkit" CreateShortCut "$SMPROGRAMS\RoRToolkit\Website.lnk" "$INSTDIR\${PRODUCT_NAME}.url" CreateShortCut "$SMPROGRAMS\RoRToolkit\Uninstall.lnk" "$INSTDIR\uninst.exe" - CreateShortCut '$SMPROGRAMS\RoRToolkit\RoR Terrain Editor.lnk' '$INSTDIR\terraineditor.py' '' '$INSTDIR\ror.ico' - CreateShortCut '$SMPROGRAMS\RoRToolkit\RoR Truck Editor.lnk' '$INSTDIR\truckeditor.py' '' '$INSTDIR\ror.ico' CreateShortCut '$SMPROGRAMS\RoRToolkit\RoR Toolkit.lnk' '$INSTDIR\rortoolkit.py' '' '$INSTDIR\ror.ico' SectionEnd Section -Post - Call ChangeRoRRepoReg + #Call ChangeRoRRepoReg WriteUninstaller "$INSTDIR\uninst.exe" WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayName" "$(^Name)" WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "UninstallString" "$INSTDIR\uninst.exe" Modified: trunk/lib_common/ror/starter.py =================================================================== --- trunk/lib_common/ror/starter.py 2007-11-27 12:55:32 UTC (rev 188) +++ trunk/lib_common/ror/starter.py 2007-11-27 13:16:15 UTC (rev 189) @@ -96,7 +96,7 @@ self.btnStartRoR.Enable(False) #self.btnStartTruckEditor.Enable(False) self.btnStartTerrainEditor.Enable(False) - self.btnBugReport.Enable(False) + #self.btnBugReport.Enable(False) self.lblRoRDir.SetLabel("Please select Rigs of Rods Directory!") else: self.btnStartRoR.Enable(True) @@ -194,7 +194,7 @@ dlg = wx.MessageDialog(self, "Update Available!\nPlease update prior submitting a BugReport!", "Info", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() - self.btnBugReport.Enable(False) + #self.btnBugReport.Enable(False) return log().info("starting bugreporter") This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-11-27 15:31:12
|
Revision: 190 http://roreditor.svn.sourceforge.net/roreditor/?rev=190&view=rev Author: rorthomas Date: 2007-11-27 07:31:10 -0800 (Tue, 27 Nov 2007) Log Message: ----------- updated setup, removed menu Modified Paths: -------------- trunk/devtools/setup/setup.nsi Added Paths: ----------- trunk/editor.ini trunk/rortoolkit.py trunk/rortoolkit_old.py Removed Paths: ------------- trunk/roreditors.py trunk/rortoolkit.py Modified: trunk/devtools/setup/setup.nsi =================================================================== --- trunk/devtools/setup/setup.nsi 2007-11-27 13:16:15 UTC (rev 189) +++ trunk/devtools/setup/setup.nsi 2007-11-27 15:31:10 UTC (rev 190) @@ -232,7 +232,7 @@ SectionIn 1 2 RO SetOutPath "$INSTDIR" SetOverwrite try - File /r /x *.pyc /x *.pyo /x doc /x devtools /x 3rdparty /x downloaded /x graphs ..\..\* + File /r /x *.pyc /x *.pyo /x doc /x devtools /x 3rdparty /x downloaded /x graphs /x linux /x lib_linux /x tools /x .svn ..\..\* SectionEnd Added: trunk/editor.ini =================================================================== --- trunk/editor.ini (rev 0) +++ trunk/editor.ini 2007-11-27 15:31:10 UTC (rev 190) @@ -0,0 +1,3 @@ +[RigsOfRods] +basepath = invalid + Deleted: trunk/roreditors.py =================================================================== --- trunk/roreditors.py 2007-11-27 13:16:15 UTC (rev 189) +++ trunk/roreditors.py 2007-11-27 15:31:10 UTC (rev 190) @@ -1,36 +0,0 @@ -#!/bin/env python -#Thomas Fischer 31/05/2007, th...@th... -import sys, os, os.path - -def main(): - """ - main method - """ - rorexecutable = '' - if sys.platform in ['linux', 'linux2']: - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_common")) - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_linux")) - rorexecutable = "RoR.bin" - elif sys.platform in ['win32']: - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_common")) - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_windows")) - rorexecutable = "RoR.exe" - - import ror.rorcommon - if not ror.rorcommon.checkRoRDirectory(): - import ror.starter - ror.starter.startApp() - - # Import Psyco if available - try: - import psyco - psyco.full() - except ImportError: - pass - - import roreditor.MainFrame - roreditor.MainFrame.startApp() - - -if __name__=="__main__": - main() \ No newline at end of file Deleted: trunk/rortoolkit.py =================================================================== --- trunk/rortoolkit.py 2007-11-27 13:16:15 UTC (rev 189) +++ trunk/rortoolkit.py 2007-11-27 15:31:10 UTC (rev 190) @@ -1,30 +0,0 @@ -#!/bin/env python -#Thomas Fischer 31/05/2007, th...@th... -import sys, os, os.path - -def main(): - """ - main method - """ - if sys.platform in ['linux', 'linux2']: - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_common")) - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_linux")) - elif sys.platform in ['win32']: - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_common")) - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_windows")) - - # Import Psyco if available - try: - import psyco - #psyco.full() - #psyco.log() - #psyco.profile() - except ImportError: - pass - - import ror.starter - ror.starter.startApp() - - -if __name__=="__main__": - main() \ No newline at end of file Copied: trunk/rortoolkit.py (from rev 187, trunk/roreditors.py) =================================================================== --- trunk/rortoolkit.py (rev 0) +++ trunk/rortoolkit.py 2007-11-27 15:31:10 UTC (rev 190) @@ -0,0 +1,36 @@ +#!/bin/env python +#Thomas Fischer 31/05/2007, th...@th... +import sys, os, os.path + +def main(): + """ + main method + """ + rorexecutable = '' + if sys.platform in ['linux', 'linux2']: + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_common")) + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_linux")) + rorexecutable = "RoR.bin" + elif sys.platform in ['win32']: + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_common")) + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_windows")) + rorexecutable = "RoR.exe" + + import ror.rorcommon + if not ror.rorcommon.checkRoRDirectory(): + import ror.starter + ror.starter.startApp() + + # Import Psyco if available + try: + import psyco + psyco.full() + except ImportError: + pass + + import roreditor.MainFrame + roreditor.MainFrame.startApp() + + +if __name__=="__main__": + main() \ No newline at end of file Copied: trunk/rortoolkit_old.py (from rev 187, trunk/rortoolkit.py) =================================================================== --- trunk/rortoolkit_old.py (rev 0) +++ trunk/rortoolkit_old.py 2007-11-27 15:31:10 UTC (rev 190) @@ -0,0 +1,30 @@ +#!/bin/env python +#Thomas Fischer 31/05/2007, th...@th... +import sys, os, os.path + +def main(): + """ + main method + """ + if sys.platform in ['linux', 'linux2']: + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_common")) + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_linux")) + elif sys.platform in ['win32']: + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_common")) + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_windows")) + + # Import Psyco if available + try: + import psyco + #psyco.full() + #psyco.log() + #psyco.profile() + except ImportError: + pass + + import ror.starter + ror.starter.startApp() + + +if __name__=="__main__": + main() \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2008-03-16 13:26:55
|
Revision: 199 http://roreditor.svn.sourceforge.net/roreditor/?rev=199&view=rev Author: rorthomas Date: 2008-03-16 06:26:41 -0700 (Sun, 16 Mar 2008) Log Message: ----------- little starter improvement, fixed spincontrol bug (not fatal now) Modified Paths: -------------- trunk/editor.ini trunk/lib_common/ror/rorcommon.py trunk/lib_common/ror/starter.py Modified: trunk/editor.ini =================================================================== --- trunk/editor.ini 2008-03-14 12:31:32 UTC (rev 198) +++ trunk/editor.ini 2008-03-16 13:26:41 UTC (rev 199) @@ -1,3 +1,3 @@ [RigsOfRods] -basepath = E:\projects\ror\main +basepath = Null Modified: trunk/lib_common/ror/rorcommon.py =================================================================== --- trunk/lib_common/ror/rorcommon.py 2008-03-14 12:31:32 UTC (rev 198) +++ trunk/lib_common/ror/rorcommon.py 2008-03-16 13:26:41 UTC (rev 199) @@ -93,7 +93,10 @@ ogre.ResourceGroupManager.getSingleton().addResourceLocation("media/materials", "FileSystem", "General", False) ogre.ResourceGroupManager.getSingleton().addResourceLocation("media/models", "FileSystem", "General", False) - ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups() + try: + ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups() + except Exception, e: + print str(e) def loadResourceFile(filename): content = [] Modified: trunk/lib_common/ror/starter.py =================================================================== --- trunk/lib_common/ror/starter.py 2008-03-14 12:31:32 UTC (rev 198) +++ trunk/lib_common/ror/starter.py 2008-03-16 13:26:41 UTC (rev 199) @@ -44,8 +44,8 @@ self.btnSelectRoRDir = wx.Button(self.panel, wx.ID_ANY, "Select RoR Directory") self.Bind(wx.EVT_BUTTON, self.OnSelectRoRDir, self.btnSelectRoRDir) - self.btnStartRoR = wx.Button(self.panel, wx.ID_ANY, "Start RoR") - self.Bind(wx.EVT_BUTTON, self.OnStartRoR, self.btnStartRoR) + #self.btnStartRoR = wx.Button(self.panel, wx.ID_ANY, "Start RoR") + #self.Bind(wx.EVT_BUTTON, self.OnStartRoR, self.btnStartRoR) if sys.platform == 'win32': self.cbbRenderEngine = wx.ComboBox(self.panel, wx.ID_ANY, RENDERSYSTEMS[0], style=wx.CB_READONLY, choices=RENDERSYSTEMS) @@ -93,13 +93,13 @@ def displayRoRDir(self): if self.rordir == "": - self.btnStartRoR.Enable(False) + #self.btnStartRoR.Enable(False) #self.btnStartTruckEditor.Enable(False) self.btnStartTerrainEditor.Enable(False) #self.btnBugReport.Enable(False) self.lblRoRDir.SetLabel("Please select Rigs of Rods Directory!") else: - self.btnStartRoR.Enable(True) + #self.btnStartRoR.Enable(True) #self.btnStartTruckEditor.Enable(True) self.btnStartTerrainEditor.Enable(True) #self.btnBugReport.Enable(True) @@ -259,7 +259,7 @@ sizer_a.Add(self.lblRoRDir, 0, wx.EXPAND, 0) sizer_a.Add(self.btnSelectRoRDir, 0, wx.EXPAND, 0) #sizer_c.Add(self.btnStartTruckEditor, 1, wx.EXPAND, 0) - sizer_a.Add(self.btnStartRoR, 0, wx.EXPAND, 0) + #sizer_a.Add(self.btnStartRoR, 0, wx.EXPAND, 0) sizer_a.Add(self.btnStartTerrainEditor, 1, wx.EXPAND, 0) if sys.platform == 'win32': This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-06-22 22:06:59
|
Revision: 7 http://roreditor.svn.sourceforge.net/roreditor/?rev=7&view=rev Author: rorthomas Date: 2007-06-22 14:56:35 -0700 (Fri, 22 Jun 2007) Log Message: ----------- deleted old stuff Removed Paths: ------------- trunk/rorextmanager/ trunk/wxtest3/ trunk/wxtest4/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-06-22 22:12:31
|
Revision: 8 http://roreditor.svn.sourceforge.net/roreditor/?rev=8&view=rev Author: rorthomas Date: 2007-06-22 15:12:29 -0700 (Fri, 22 Jun 2007) Log Message: ----------- initial rortoolkit Added Paths: ----------- trunk/Plugin_BSPSceneManager.dll trunk/Plugin_CgProgramManager.dll trunk/Plugin_OctreeSceneManager.dll trunk/Plugin_ParticleFX.dll trunk/RenderSystem_Direct3D9.dll trunk/RenderSystem_GL.dll trunk/dxwebsetup.exe trunk/editor.cfg trunk/lib/ trunk/lib/ogre/ trunk/lib/ogre/__init__.py trunk/lib/ogre/gui/ trunk/lib/ogre/gui/CEGUI/ trunk/lib/ogre/gui/CEGUI/CEGUIBase.dll trunk/lib/ogre/gui/CEGUI/CEGUIExpatParser.dll trunk/lib/ogre/gui/CEGUI/CEGUIFalagardWRBase.dll trunk/lib/ogre/gui/CEGUI/OgreGUIRenderer.dll trunk/lib/ogre/gui/CEGUI/__init__.py trunk/lib/ogre/gui/CEGUI/_cegui_.pyd trunk/lib/ogre/gui/__init__.py trunk/lib/ogre/io/ trunk/lib/ogre/io/OIS/ trunk/lib/ogre/io/OIS/OIS.dll trunk/lib/ogre/io/OIS/__init__.py trunk/lib/ogre/io/OIS/_ois_.pyd trunk/lib/ogre/io/__init__.py trunk/lib/ogre/physics/ trunk/lib/ogre/physics/ODE/ trunk/lib/ogre/physics/ODE/__init__.py trunk/lib/ogre/physics/ODE/_ode_.pyd trunk/lib/ogre/physics/ODE/ode.dll trunk/lib/ogre/physics/OgreNewt/ trunk/lib/ogre/physics/OgreNewt/Newton.dll trunk/lib/ogre/physics/OgreNewt/__init__.py trunk/lib/ogre/physics/OgreNewt/_ogrenewt_.pyd trunk/lib/ogre/physics/OgreOde/ trunk/lib/ogre/physics/OgreOde/OgreOde_Core.dll trunk/lib/ogre/physics/OgreOde/OgreOde_Loader.dll trunk/lib/ogre/physics/OgreOde/OgreOde_Prefab.dll trunk/lib/ogre/physics/OgreOde/__init__.py trunk/lib/ogre/physics/OgreOde/_ogreode_.pyd trunk/lib/ogre/physics/OgreOde/ode.dll trunk/lib/ogre/physics/OgreRefApp/ trunk/lib/ogre/physics/OgreRefApp/ReferenceAppLayer.dll trunk/lib/ogre/physics/OgreRefApp/__init__.py trunk/lib/ogre/physics/OgreRefApp/_ogrerefapp_.pyd trunk/lib/ogre/physics/OgreRefApp/ode.dll trunk/lib/ogre/physics/__init__.py trunk/lib/ogre/renderer/ trunk/lib/ogre/renderer/OGRE/ trunk/lib/ogre/renderer/OGRE/OgreMain.dll trunk/lib/ogre/renderer/OGRE/__init__.py trunk/lib/ogre/renderer/OGRE/_ogre_.pyd trunk/lib/ogre/renderer/OGRE/_ogre_exceptions_.py trunk/lib/ogre/renderer/OGRE/boost_python-vc71-mt-1_35.dll trunk/lib/ogre/renderer/OGRE/cg.dll trunk/lib/ogre/renderer/OGRE/named_tuple.py trunk/lib/ogre/renderer/OGRE/sf_OIS.py trunk/lib/ogre/renderer/OGRE/sf_utils.py trunk/lib/ogre/renderer/__init__.py trunk/lib/ogre/sound/ trunk/lib/ogre/sound/OgreAL/ trunk/lib/ogre/sound/OgreAL/OgreAL.dll trunk/lib/ogre/sound/OgreAL/OpenAL32.dll trunk/lib/ogre/sound/OgreAL/__init__.py trunk/lib/ogre/sound/OgreAL/_ogreal_.pyd trunk/lib/ogre/sound/OgreAL/alut.dll trunk/lib/ogre/sound/OgreAL/ogg.dll trunk/lib/ogre/sound/OgreAL/vorbis.dll trunk/lib/ogre/sound/OgreAL/vorbisfile.dll trunk/lib/ogre/sound/OgreAL/wrap_oal.dll trunk/lib/ogre/sound/__init__.py trunk/lib/ror/ trunk/lib/ror/RoROgreWindow.py trunk/lib/ror/SettingsFrame.py trunk/lib/ror/SharedTestOgreWindow.py trunk/lib/ror/__init__.py trunk/lib/ror/editor.cfg trunk/lib/ror/ror.ico trunk/lib/ror/rorcommon.py trunk/lib/ror/rorsettings.py trunk/lib/ror/settingsdialog.py trunk/lib/ror/splash.bmp trunk/lib/ror/starter.py trunk/lib/ror/truckparser.py trunk/lib/rorterraineditor/ trunk/lib/rorterraineditor/HelpFrame.py trunk/lib/rorterraineditor/MainFrame.py trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py trunk/lib/rorterraineditor/RoRTerrainSelectedObjectOgreWindow.py trunk/lib/rorterraineditor/RoRTerrainSelectedObjectTopOgreWindow.py trunk/lib/rorterraineditor/TerrainOgreWindow.py_ trunk/lib/rorterraineditor/__init__.py trunk/lib/rortruckeditor/ trunk/lib/rortruckeditor/MainFrame.py trunk/lib/rortruckeditor/RoRTruckOgreWindow.py trunk/lib/rortruckeditor/RoRUVOgreWindow.py trunk/lib/rortruckeditor/UVFrame.py trunk/lib/rortruckeditor/__init__.py trunk/lib/testapp/ trunk/lib/wx/ trunk/lib/wx/__init__.py trunk/lib/wx/__version__.py trunk/lib/wx/_activex.pyd trunk/lib/wx/_animate.pyd trunk/lib/wx/_aui.pyd trunk/lib/wx/_calendar.pyd trunk/lib/wx/_combo.pyd trunk/lib/wx/_controls.py trunk/lib/wx/_controls_.pyd trunk/lib/wx/_core.py trunk/lib/wx/_core_.pyd trunk/lib/wx/_gdi.py trunk/lib/wx/_gdi_.pyd trunk/lib/wx/_gizmos.pyd trunk/lib/wx/_glcanvas.pyd trunk/lib/wx/_grid.pyd trunk/lib/wx/_html.pyd trunk/lib/wx/_media.pyd trunk/lib/wx/_misc.py trunk/lib/wx/_misc_.pyd trunk/lib/wx/_richtext.pyd trunk/lib/wx/_stc.pyd trunk/lib/wx/_webkit.pyd trunk/lib/wx/_windows.py trunk/lib/wx/_windows_.pyd trunk/lib/wx/_wizard.pyd trunk/lib/wx/_xrc.pyd trunk/lib/wx/activex.py trunk/lib/wx/animate.py trunk/lib/wx/aui.py trunk/lib/wx/build/ trunk/lib/wx/build/__init__.py trunk/lib/wx/build/build_options.py trunk/lib/wx/build/config.py trunk/lib/wx/calendar.py trunk/lib/wx/combo.py trunk/lib/wx/gdiplus.dll trunk/lib/wx/gizmos.py trunk/lib/wx/glcanvas.py trunk/lib/wx/grid.py trunk/lib/wx/html.py trunk/lib/wx/lib/ trunk/lib/wx/lib/CDate.py trunk/lib/wx/lib/ClickableHtmlWindow.py trunk/lib/wx/lib/__init__.py trunk/lib/wx/lib/activexwrapper.py trunk/lib/wx/lib/analogclock/ trunk/lib/wx/lib/analogclock/__init__.py trunk/lib/wx/lib/analogclock/analogclock.py trunk/lib/wx/lib/analogclock/helpers.py trunk/lib/wx/lib/analogclock/lib_setup/ trunk/lib/wx/lib/analogclock/lib_setup/__init__.py trunk/lib/wx/lib/analogclock/lib_setup/buttontreectrlpanel.py trunk/lib/wx/lib/analogclock/lib_setup/colourselect.py trunk/lib/wx/lib/analogclock/lib_setup/fontselect.py trunk/lib/wx/lib/analogclock/setup.py trunk/lib/wx/lib/analogclock/styles.py trunk/lib/wx/lib/anchors.py trunk/lib/wx/lib/art/ trunk/lib/wx/lib/art/__init__.py trunk/lib/wx/lib/art/flagart.py trunk/lib/wx/lib/art/img2pyartprov.py trunk/lib/wx/lib/buttonpanel.py trunk/lib/wx/lib/buttons.py trunk/lib/wx/lib/calendar.py trunk/lib/wx/lib/colourchooser/ trunk/lib/wx/lib/colourchooser/__init__.py trunk/lib/wx/lib/colourchooser/canvas.py trunk/lib/wx/lib/colourchooser/intl.py trunk/lib/wx/lib/colourchooser/pycolourbox.py trunk/lib/wx/lib/colourchooser/pycolourchooser.py trunk/lib/wx/lib/colourchooser/pycolourslider.py trunk/lib/wx/lib/colourchooser/pypalette.py trunk/lib/wx/lib/colourdb.py trunk/lib/wx/lib/colourselect.py trunk/lib/wx/lib/combotreebox.py trunk/lib/wx/lib/customtreectrl.py trunk/lib/wx/lib/delayedresult.py trunk/lib/wx/lib/dialogs.py trunk/lib/wx/lib/docview.py trunk/lib/wx/lib/dragscroller.py trunk/lib/wx/lib/editor/ trunk/lib/wx/lib/editor/README.txt trunk/lib/wx/lib/editor/__init__.py trunk/lib/wx/lib/editor/editor.py trunk/lib/wx/lib/editor/images.py trunk/lib/wx/lib/editor/selection.py trunk/lib/wx/lib/evtmgr.py trunk/lib/wx/lib/expando.py trunk/lib/wx/lib/fancytext.py trunk/lib/wx/lib/filebrowsebutton.py trunk/lib/wx/lib/flashwin.py trunk/lib/wx/lib/flatnotebook.py trunk/lib/wx/lib/floatbar.py trunk/lib/wx/lib/floatcanvas/ trunk/lib/wx/lib/floatcanvas/FloatCanvas.py trunk/lib/wx/lib/floatcanvas/NavCanvas.py trunk/lib/wx/lib/floatcanvas/Resources.py trunk/lib/wx/lib/floatcanvas/__init__.py trunk/lib/wx/lib/foldmenu.py trunk/lib/wx/lib/foldpanelbar.py trunk/lib/wx/lib/gestures.py trunk/lib/wx/lib/gridmovers.py trunk/lib/wx/lib/grids.py trunk/lib/wx/lib/hyperlink.py trunk/lib/wx/lib/iewin.py trunk/lib/wx/lib/imagebrowser.py trunk/lib/wx/lib/imageutils.py trunk/lib/wx/lib/infoframe.py trunk/lib/wx/lib/inspection.py trunk/lib/wx/lib/intctrl.py trunk/lib/wx/lib/langlistctrl.py trunk/lib/wx/lib/layoutf.py trunk/lib/wx/lib/masked/ trunk/lib/wx/lib/masked/__init__.py trunk/lib/wx/lib/masked/combobox.py trunk/lib/wx/lib/masked/ctrl.py trunk/lib/wx/lib/masked/ipaddrctrl.py trunk/lib/wx/lib/masked/maskededit.py trunk/lib/wx/lib/masked/numctrl.py trunk/lib/wx/lib/masked/textctrl.py trunk/lib/wx/lib/masked/timectrl.py trunk/lib/wx/lib/mixins/ trunk/lib/wx/lib/mixins/__init__.py trunk/lib/wx/lib/mixins/grid.py trunk/lib/wx/lib/mixins/imagelist.py trunk/lib/wx/lib/mixins/inspection.py trunk/lib/wx/lib/mixins/listctrl.py trunk/lib/wx/lib/mixins/rubberband.py trunk/lib/wx/lib/mixins/treemixin.py trunk/lib/wx/lib/multisash.py trunk/lib/wx/lib/mvctree.py trunk/lib/wx/lib/newevent.py trunk/lib/wx/lib/ogl/ trunk/lib/wx/lib/ogl/__init__.py trunk/lib/wx/lib/ogl/_basic.py trunk/lib/wx/lib/ogl/_bmpshape.py trunk/lib/wx/lib/ogl/_canvas.py trunk/lib/wx/lib/ogl/_composit.py trunk/lib/wx/lib/ogl/_diagram.py trunk/lib/wx/lib/ogl/_divided.py trunk/lib/wx/lib/ogl/_drawn.py trunk/lib/wx/lib/ogl/_lines.py trunk/lib/wx/lib/ogl/_oglmisc.py trunk/lib/wx/lib/pdfwin.py trunk/lib/wx/lib/plot.py trunk/lib/wx/lib/popupctl.py trunk/lib/wx/lib/printout.py trunk/lib/wx/lib/pubsub.py trunk/lib/wx/lib/pydocview.py trunk/lib/wx/lib/pyshell.py trunk/lib/wx/lib/rcsizer.py trunk/lib/wx/lib/rightalign.py trunk/lib/wx/lib/rpcMixin.py trunk/lib/wx/lib/scrolledpanel.py trunk/lib/wx/lib/sheet.py trunk/lib/wx/lib/shell.py trunk/lib/wx/lib/splashscreen.py trunk/lib/wx/lib/splitter.py trunk/lib/wx/lib/statbmp.py trunk/lib/wx/lib/stattext.py trunk/lib/wx/lib/throbber.py trunk/lib/wx/lib/ticker.py trunk/lib/wx/lib/ticker_xrc.py trunk/lib/wx/lib/vtk.py trunk/lib/wx/lib/wordwrap.py trunk/lib/wx/lib/wxPlotCanvas.py trunk/lib/wx/lib/wxpTag.py trunk/lib/wx/locale/ trunk/lib/wx/locale/af/ trunk/lib/wx/locale/af/LC_MESSAGES/ trunk/lib/wx/locale/af/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/ca/ trunk/lib/wx/locale/ca/LC_MESSAGES/ trunk/lib/wx/locale/ca/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/cs/ trunk/lib/wx/locale/cs/LC_MESSAGES/ trunk/lib/wx/locale/cs/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/da/ trunk/lib/wx/locale/da/LC_MESSAGES/ trunk/lib/wx/locale/da/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/de/ trunk/lib/wx/locale/de/LC_MESSAGES/ trunk/lib/wx/locale/de/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/el/ trunk/lib/wx/locale/el/LC_MESSAGES/ trunk/lib/wx/locale/el/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/es/ trunk/lib/wx/locale/es/LC_MESSAGES/ trunk/lib/wx/locale/es/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/eu/ trunk/lib/wx/locale/eu/LC_MESSAGES/ trunk/lib/wx/locale/eu/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/fi/ trunk/lib/wx/locale/fi/LC_MESSAGES/ trunk/lib/wx/locale/fi/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/fr/ trunk/lib/wx/locale/fr/LC_MESSAGES/ trunk/lib/wx/locale/fr/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/gl_ES/ trunk/lib/wx/locale/gl_ES/LC_MESSAGES/ trunk/lib/wx/locale/gl_ES/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/hi/ trunk/lib/wx/locale/hi/LC_MESSAGES/ trunk/lib/wx/locale/hi/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/hu/ trunk/lib/wx/locale/hu/LC_MESSAGES/ trunk/lib/wx/locale/hu/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/id/ trunk/lib/wx/locale/id/LC_MESSAGES/ trunk/lib/wx/locale/id/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/it/ trunk/lib/wx/locale/it/LC_MESSAGES/ trunk/lib/wx/locale/it/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/ja/ trunk/lib/wx/locale/ja/LC_MESSAGES/ trunk/lib/wx/locale/ja/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/lv/ trunk/lib/wx/locale/lv/LC_MESSAGES/ trunk/lib/wx/locale/lv/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/ms/ trunk/lib/wx/locale/ms/LC_MESSAGES/ trunk/lib/wx/locale/ms/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/nb/ trunk/lib/wx/locale/nb/LC_MESSAGES/ trunk/lib/wx/locale/nb/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/nl/ trunk/lib/wx/locale/nl/LC_MESSAGES/ trunk/lib/wx/locale/nl/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/pl/ trunk/lib/wx/locale/pl/LC_MESSAGES/ trunk/lib/wx/locale/pl/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/pt_BR/ trunk/lib/wx/locale/pt_BR/LC_MESSAGES/ trunk/lib/wx/locale/pt_BR/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/ru/ trunk/lib/wx/locale/ru/LC_MESSAGES/ trunk/lib/wx/locale/ru/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/sl/ trunk/lib/wx/locale/sl/LC_MESSAGES/ trunk/lib/wx/locale/sl/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/sq/ trunk/lib/wx/locale/sq/LC_MESSAGES/ trunk/lib/wx/locale/sq/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/sv/ trunk/lib/wx/locale/sv/LC_MESSAGES/ trunk/lib/wx/locale/sv/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/tr/ trunk/lib/wx/locale/tr/LC_MESSAGES/ trunk/lib/wx/locale/tr/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/uk/ trunk/lib/wx/locale/uk/LC_MESSAGES/ trunk/lib/wx/locale/uk/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/zh_CN/ trunk/lib/wx/locale/zh_CN/LC_MESSAGES/ trunk/lib/wx/locale/zh_CN/LC_MESSAGES/wxstd.mo trunk/lib/wx/locale/zh_TW/ trunk/lib/wx/locale/zh_TW/LC_MESSAGES/ trunk/lib/wx/locale/zh_TW/LC_MESSAGES/wxstd.mo trunk/lib/wx/media.py trunk/lib/wx/msvcp71.dll trunk/lib/wx/py/ trunk/lib/wx/py/CHANGES.txt trunk/lib/wx/py/Py.ico trunk/lib/wx/py/PyAlaCarte.py trunk/lib/wx/py/PyAlaMode.py trunk/lib/wx/py/PyAlaModeTest.py trunk/lib/wx/py/PyCrust.ico trunk/lib/wx/py/PyCrust.py trunk/lib/wx/py/PyCrust_16.png trunk/lib/wx/py/PyCrust_32.png trunk/lib/wx/py/PyFilling.py trunk/lib/wx/py/PyShell.py trunk/lib/wx/py/PyWrap.py trunk/lib/wx/py/README.txt trunk/lib/wx/py/__init__.py trunk/lib/wx/py/buffer.py trunk/lib/wx/py/crust.py trunk/lib/wx/py/dispatcher.py trunk/lib/wx/py/document.py trunk/lib/wx/py/editor.py trunk/lib/wx/py/editwindow.py trunk/lib/wx/py/filling.py trunk/lib/wx/py/frame.py trunk/lib/wx/py/images.py trunk/lib/wx/py/interpreter.py trunk/lib/wx/py/introspect.py trunk/lib/wx/py/pseudo.py trunk/lib/wx/py/shell.py trunk/lib/wx/py/tests/ trunk/lib/wx/py/tests/test_interpreter.py trunk/lib/wx/py/tests/test_introspect.py trunk/lib/wx/py/tests/test_pseudo.py trunk/lib/wx/py/tests/test_version.py trunk/lib/wx/py/tests/testall.py trunk/lib/wx/py/version.py trunk/lib/wx/richtext.py trunk/lib/wx/stc.py trunk/lib/wx/tools/ trunk/lib/wx/tools/__init__.py trunk/lib/wx/tools/dbg.py trunk/lib/wx/tools/genaxmodule.py trunk/lib/wx/tools/helpviewer.py trunk/lib/wx/tools/img2img.py trunk/lib/wx/tools/img2png.py trunk/lib/wx/tools/img2py.py trunk/lib/wx/tools/img2xpm.py trunk/lib/wx/tools/pywxrc.py trunk/lib/wx/webkit.py trunk/lib/wx/wizard.py trunk/lib/wx/wxbase28h_net_vc.dll trunk/lib/wx/wxbase28h_vc.dll trunk/lib/wx/wxbase28h_xml_vc.dll trunk/lib/wx/wxmsw28h_adv_vc.dll trunk/lib/wx/wxmsw28h_aui_vc.dll trunk/lib/wx/wxmsw28h_core_vc.dll trunk/lib/wx/wxmsw28h_gizmos_vc.dll trunk/lib/wx/wxmsw28h_gizmos_xrc_vc.dll trunk/lib/wx/wxmsw28h_gl_vc.dll trunk/lib/wx/wxmsw28h_html_vc.dll trunk/lib/wx/wxmsw28h_media_vc.dll trunk/lib/wx/wxmsw28h_qa_vc.dll trunk/lib/wx/wxmsw28h_richtext_vc.dll trunk/lib/wx/wxmsw28h_stc_vc.dll trunk/lib/wx/wxmsw28h_xrc_vc.dll trunk/lib/wx/xrc.py trunk/lib/wxogre/ trunk/lib/wxogre/OgreManager.py trunk/lib/wxogre/__init__.py trunk/lib/wxogre/wxOgreWindow.py trunk/media/ trunk/media/gui/ trunk/media/gui/OpenFile.gif trunk/media/materials/ trunk/media/materials/beams.material trunk/media/materials/clouds.jpg trunk/media/materials/dirt-grass.jpg trunk/media/materials/mysimple.material trunk/media/materials/nodes.material trunk/media/materials/uvbg.png trunk/media/materials/uveditor.material trunk/media/materials/water.jpg trunk/media/models/ trunk/media/models/arrow.mesh trunk/media/models/box.mesh trunk/media/models/cap_cap.mesh trunk/media/models/cap_mid.mesh trunk/media/models/circlepointer.mesh trunk/media/models/ellipsoid.mesh trunk/media/models/roundarrow.mesh trunk/media/models/wheel.mesh trunk/media/packs/ trunk/media/packs/OgreCore.zip trunk/media/packs/skybox.zip trunk/ogre.cfg trunk/plugins.cfg trunk/readme-installer.txt trunk/readme.txt trunk/ror.ico trunk/rortoolkit.bat trunk/rortoolkit.py trunk/setup.nsi trunk/splash.bmp trunk/terraineditor.bat trunk/terraineditor.py trunk/truckeditor.bat trunk/truckeditor.py Added: trunk/Plugin_BSPSceneManager.dll =================================================================== (Binary files differ) Property changes on: trunk/Plugin_BSPSceneManager.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/Plugin_CgProgramManager.dll =================================================================== (Binary files differ) Property changes on: trunk/Plugin_CgProgramManager.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/Plugin_OctreeSceneManager.dll =================================================================== (Binary files differ) Property changes on: trunk/Plugin_OctreeSceneManager.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/Plugin_ParticleFX.dll =================================================================== (Binary files differ) Property changes on: trunk/Plugin_ParticleFX.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/RenderSystem_Direct3D9.dll =================================================================== (Binary files differ) Property changes on: trunk/RenderSystem_Direct3D9.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/RenderSystem_GL.dll =================================================================== (Binary files differ) Property changes on: trunk/RenderSystem_GL.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/dxwebsetup.exe =================================================================== (Binary files differ) Property changes on: trunk/dxwebsetup.exe ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/editor.cfg =================================================================== --- trunk/editor.cfg (rev 0) +++ trunk/editor.cfg 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1 @@ +C:\games\RoR-0.31a_\RoR.exe \ No newline at end of file Added: trunk/lib/ogre/__init__.py =================================================================== --- trunk/lib/ogre/__init__.py (rev 0) +++ trunk/lib/ogre/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1 @@ +#keep me \ No newline at end of file Added: trunk/lib/ogre/gui/CEGUI/CEGUIBase.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/gui/CEGUI/CEGUIBase.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/gui/CEGUI/CEGUIExpatParser.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/gui/CEGUI/CEGUIExpatParser.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/gui/CEGUI/CEGUIFalagardWRBase.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/gui/CEGUI/CEGUIFalagardWRBase.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/gui/CEGUI/OgreGUIRenderer.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/gui/CEGUI/OgreGUIRenderer.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/gui/CEGUI/__init__.py =================================================================== --- trunk/lib/ogre/gui/CEGUI/__init__.py (rev 0) +++ trunk/lib/ogre/gui/CEGUI/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1,7 @@ +import sys, os + +## we need the path for additional CEGUI dll's +if sys.platform == 'win32': + os.environ['PATH'] += ';' + __path__[0] + +from _cegui_ import * \ No newline at end of file Added: trunk/lib/ogre/gui/CEGUI/_cegui_.pyd =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/gui/CEGUI/_cegui_.pyd ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/gui/__init__.py =================================================================== --- trunk/lib/ogre/gui/__init__.py (rev 0) +++ trunk/lib/ogre/gui/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1 @@ +#keep me \ No newline at end of file Added: trunk/lib/ogre/io/OIS/OIS.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/io/OIS/OIS.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/io/OIS/__init__.py =================================================================== --- trunk/lib/ogre/io/OIS/__init__.py (rev 0) +++ trunk/lib/ogre/io/OIS/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1 @@ +from _ois_ import * Added: trunk/lib/ogre/io/OIS/_ois_.pyd =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/io/OIS/_ois_.pyd ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/io/__init__.py =================================================================== --- trunk/lib/ogre/io/__init__.py (rev 0) +++ trunk/lib/ogre/io/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1 @@ +#keep me \ No newline at end of file Added: trunk/lib/ogre/physics/ODE/__init__.py =================================================================== --- trunk/lib/ogre/physics/ODE/__init__.py (rev 0) +++ trunk/lib/ogre/physics/ODE/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1 @@ +from _ode_ import * \ No newline at end of file Added: trunk/lib/ogre/physics/ODE/_ode_.pyd =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/physics/ODE/_ode_.pyd ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/physics/ODE/ode.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/physics/ODE/ode.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/physics/OgreNewt/Newton.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/physics/OgreNewt/Newton.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/physics/OgreNewt/__init__.py =================================================================== --- trunk/lib/ogre/physics/OgreNewt/__init__.py (rev 0) +++ trunk/lib/ogre/physics/OgreNewt/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1 @@ +from _ogrenewt_ import * \ No newline at end of file Added: trunk/lib/ogre/physics/OgreNewt/_ogrenewt_.pyd =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/physics/OgreNewt/_ogrenewt_.pyd ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/physics/OgreOde/OgreOde_Core.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/physics/OgreOde/OgreOde_Core.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/physics/OgreOde/OgreOde_Loader.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/physics/OgreOde/OgreOde_Loader.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/physics/OgreOde/OgreOde_Prefab.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/physics/OgreOde/OgreOde_Prefab.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/physics/OgreOde/__init__.py =================================================================== --- trunk/lib/ogre/physics/OgreOde/__init__.py (rev 0) +++ trunk/lib/ogre/physics/OgreOde/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1 @@ +from _ogreode_ import * \ No newline at end of file Added: trunk/lib/ogre/physics/OgreOde/_ogreode_.pyd =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/physics/OgreOde/_ogreode_.pyd ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/physics/OgreOde/ode.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/physics/OgreOde/ode.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/physics/OgreRefApp/ReferenceAppLayer.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/physics/OgreRefApp/ReferenceAppLayer.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/physics/OgreRefApp/__init__.py =================================================================== --- trunk/lib/ogre/physics/OgreRefApp/__init__.py (rev 0) +++ trunk/lib/ogre/physics/OgreRefApp/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1 @@ +from _ogrerefapp_ import * \ No newline at end of file Added: trunk/lib/ogre/physics/OgreRefApp/_ogrerefapp_.pyd =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/physics/OgreRefApp/_ogrerefapp_.pyd ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/physics/OgreRefApp/ode.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/physics/OgreRefApp/ode.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/physics/__init__.py =================================================================== --- trunk/lib/ogre/physics/__init__.py (rev 0) +++ trunk/lib/ogre/physics/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1 @@ +#keep me \ No newline at end of file Added: trunk/lib/ogre/renderer/OGRE/OgreMain.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/renderer/OGRE/OgreMain.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/renderer/OGRE/__init__.py =================================================================== --- trunk/lib/ogre/renderer/OGRE/__init__.py (rev 0) +++ trunk/lib/ogre/renderer/OGRE/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1,36 @@ +import sys, os + +if sys.platform == 'win32': + os.environ['PATH'] += ';' + __path__[0] + +from _ogre_ import * +from _ogre_exceptions_ import * + + +## Note the work around to ensure the Radians and Degree types work correctly +## the problem is the constructors are overloaded in each class and passing a real to +## Radian actually causes boost to try it as a Degree first, and as Degreee has a 'Real' overload +## it create the Degree and passes it back to Radian -- +## +## and as it's a lot of work and overly confusing to fix this in generate_code.py we fix it here +## +def Radian( r=None, d=None ): + if isinstance( r, _ogre_.Degree ): + return _ogre_.Radian( r ) + elif isinstance( r, _ogre_.Radian ): + return _ogre_.Radian().assign( r ) + elif d: + return _ogre_.Radian( d=d ) + else: + return _ogre_.Radian( r=r ) + +def Degree( d=None, r=None ): + if isinstance( d, _ogre_.Radian ): + return _ogre_.Degree( d ) + elif isinstance( d, _ogre_.Degree ): + return _ogre_.Degree().assign( d ) + elif r: + return _ogre.Degree (r=r) + else: + return _ogre_.Degree( d=d ) + Added: trunk/lib/ogre/renderer/OGRE/_ogre_.pyd =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/renderer/OGRE/_ogre_.pyd ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/renderer/OGRE/_ogre_exceptions_.py =================================================================== --- trunk/lib/ogre/renderer/OGRE/_ogre_exceptions_.py (rev 0) +++ trunk/lib/ogre/renderer/OGRE/_ogre_exceptions_.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1,110 @@ +import _ogre_ + +class OgreException(Exception): + def __init__( self, app_error ): + Exception.__init__( self ) + self._pimpl = app_error + + def __str__( self ): + return self._pimpl.getFullDescription() + + def __getattribute__(self, attr): + my_pimpl = super(OgreException, self).__getattribute__("_pimpl") + try: + return getattr(my_pimpl, attr) + except AttributeError: + return super(OgreException,self).__getattribute__(attr) + +_ogre_.OgreException = OgreException +#this one for backward compatability +_ogre_.Exception = OgreException + +class OgreItemIdentityException(OgreException): + def __init__( self, app_error ): + OgreException.__init__( self, app_error ) + + def __getattribute__(self, attr): + return super(OgreItemIdentityException,self).__getattribute__(attr) + +_ogre_._ItemIdentityException_.py_err_class = OgreItemIdentityException +_ogre_.OgreItemIdentityException = OgreItemIdentityException + +class OgreInternalErrorException(OgreException): + def __init__( self, app_error ): + OgreException.__init__( self, app_error ) + + def __getattribute__(self, attr): + return super(OgreInternalErrorException,self).__getattribute__(attr) + +_ogre_._InternalErrorException_.py_err_class = OgreInternalErrorException +_ogre_.OgreInternalErrorException = OgreInternalErrorException + +class OgreRenderingAPIException(OgreException): + def __init__( self, app_error ): + OgreException.__init__( self, app_error ) + + def __getattribute__(self, attr): + return super(OgreRenderingAPIException,self).__getattribute__(attr) + +_ogre_._RenderingAPIException_.py_err_class = OgreRenderingAPIException +_ogre_.OgreRenderingAPIException = OgreRenderingAPIException + +class OgreRuntimeAssertionException(OgreException): + def __init__( self, app_error ): + OgreException.__init__( self, app_error ) + + def __getattribute__(self, attr): + return super(OgreRuntimeAssertionException,self).__getattribute__(attr) + +_ogre_._RuntimeAssertionException_.py_err_class = OgreRuntimeAssertionException +_ogre_.OgreRuntimeAssertionException = OgreRuntimeAssertionException + +class OgreInvalidParametersException(OgreException): + def __init__( self, app_error ): + OgreException.__init__( self, app_error ) + + def __getattribute__(self, attr): + return super(OgreInvalidParametersException,self).__getattribute__(attr) + +_ogre_._InvalidParametersException_.py_err_class = OgreInvalidParametersException +_ogre_.OgreInvalidParametersException = OgreInvalidParametersException + +class OgreInvalidStateException(OgreException): + def __init__( self, app_error ): + OgreException.__init__( self, app_error ) + + def __getattribute__(self, attr): + return super(OgreInvalidStateException,self).__getattribute__(attr) + +_ogre_._InvalidStateException_.py_err_class = OgreInvalidStateException +_ogre_.OgreInvalidStateException = OgreInvalidStateException + +class OgreIOException(OgreException): + def __init__( self, app_error ): + OgreException.__init__( self, app_error ) + + def __getattribute__(self, attr): + return super(OgreIOException,self).__getattribute__(attr) + +_ogre_._IOException_.py_err_class = OgreIOException +_ogre_.OgreIOException = OgreIOException + +class OgreFileNotFoundException(OgreException): + def __init__( self, app_error ): + OgreException.__init__( self, app_error ) + + def __getattribute__(self, attr): + return super(OgreFileNotFoundException,self).__getattribute__(attr) + +_ogre_._FileNotFoundException_.py_err_class = OgreFileNotFoundException +_ogre_.OgreFileNotFoundException = OgreFileNotFoundException + +class OgreUnimplementedException(OgreException): + def __init__( self, app_error ): + OgreException.__init__( self, app_error ) + + def __getattribute__(self, attr): + return super(OgreUnimplementedException,self).__getattribute__(attr) + +_ogre_._UnimplementedException_.py_err_class = OgreUnimplementedException +_ogre_.OgreUnimplementedException = OgreUnimplementedException \ No newline at end of file Added: trunk/lib/ogre/renderer/OGRE/boost_python-vc71-mt-1_35.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/renderer/OGRE/boost_python-vc71-mt-1_35.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/renderer/OGRE/cg.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/renderer/OGRE/cg.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/renderer/OGRE/named_tuple.py =================================================================== --- trunk/lib/ogre/renderer/OGRE/named_tuple.py (rev 0) +++ trunk/lib/ogre/renderer/OGRE/named_tuple.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1,46 @@ +# This file has been generated by Py++. + +# Copyright 2004 Roman Yakovenko. +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# http://www.boost.org/LICENSE_1_0.txt) + +class named_tuple(tuple): + """Creates tuple, which allows access to stored values by name and\or by index. + + Construction example: named_tuple( ('a',0), ('b',1) ) + 'a' and 'b' are names, while 0 and 1 are values + """ + + def __new__(cls, *args): + return tuple.__new__( cls, [ val for name, val in args] ) + + def __init__(self, *args): + tuple.__init__( self ) + self.__dict__[ '__name2value' ] = dict( args ) + + def __getattr__(self, name): + try: + return self.__dict__['__name2value'][ name ] + except KeyError: + raise AttributeError( "named_tuple has no attribute '%s'" % name ) + + def __setattr__(self, name, value): + raise AttributeError( "named_tuple has no attribute '%s'" % name ) + + def __getitem__( self, key ): + #TODO: it could be nice to support slicing. So the __getitem__ in case of + #slicing will return new named_tuple. + if isinstance( key, basestring ): + return self.__dict__['__name2value'][ key ] + else: + return super( named_tuple, self ).__getitem__( key ) + +if __name__ == '__main__': + nt = named_tuple( ('a',0), ('b',1) ) + assert nt.a == 0 and nt.b == 1 + a,b = nt + assert a == 0 and b == 1 + assert nt[ "a" ] == 0 and nt[ "b" ] == 1 + + Added: trunk/lib/ogre/renderer/OGRE/sf_OIS.py =================================================================== --- trunk/lib/ogre/renderer/OGRE/sf_OIS.py (rev 0) +++ trunk/lib/ogre/renderer/OGRE/sf_OIS.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1,448 @@ +# This code is in the Public Domain +# ----------------------------------------------------------------------------- +# This source file is part of Python-Ogre +# For the latest info, see http://python-ogre.org/ +# +# It is likely based on original code from OGRE and/or PyOgre +# For the latest info, see http://www.ogre3d.org/ +# +# You may use this sample code for anything you like, it is not covered by the +# LGPL. +# ----------------------------------------------------------------------------- +import ogre.renderer.OGRE as ogre +import ogre.io.OIS as OIS +###import OgreRefApp + +def getPluginPath(): + """Return the absolute path to a valid plugins.cfg file.""" + import sys + import os + import os.path + + paths = [os.path.join(os.getcwd(), 'plugins.cfg'), + '/etc/OGRE/plugins.cfg', + os.path.join(os.path.dirname(os.path.abspath(__file__)), + 'plugins.cfg')] + for path in paths: + if os.path.exists(path): + return path + + sys.stderr.write("\n" + "** Warning: Unable to locate a suitable plugins.cfg file.\n" + "** Warning: Please check your ogre installation and copy a\n" + "** Warning: working plugins.cfg file to the current directory.\n\n") + raise ogre.Exception(0, "can't locate the 'plugins.cfg' file", "") + +class Application(object): + "This class is the base for an Ogre application." + debugText="" + + def __init__(self): + self.frameListener = None + self.root = None + self.camera = None + self.renderWindow = None + self.sceneManager = None + self.world = None + + def __del__(self): + "Clear variables, this should not actually be needed." + del self.camera + del self.sceneManager + del self.frameListener + if self.world: + del self.world + del self.root + del self.renderWindow + + def go(self): + "Starts the rendering loop." + if not self._setUp(): + return + if self._isPsycoEnabled(): + self._activatePsyco() + self.root.startRendering() + + + def _setUp(self): + """This sets up the ogre application, and returns false if the user + hits "cancel" in the dialog box.""" + self.root = ogre.Root(getPluginPath()) + self.root.setFrameSmoothingPeriod (5.0) + + self._setUpResources() + if not self._configure(): + return False + + self._chooseSceneManager() + self._createWorld() + self._createCamera() + self._createViewports() + + ogre.TextureManager.getSingleton().setDefaultNumMipmaps (5) + + self._createResourceListener() + self._loadResources() + + self._createScene() + self._createFrameListener() + return True + + def _setUpResources(self): + """This sets up Ogre's resources, which are required to be in + resources.cfg.""" + config = ogre.ConfigFile() + config.load('resources.cfg' ) + seci = config.getSectionIterator() + while seci.hasMoreElements(): + SectionName = seci.peekNextKey() + Section = seci.getNext() + for item in Section: + ogre.ResourceGroupManager.getSingleton().\ + addResourceLocation(item.value, item.key, SectionName) + + def _createResourceListener(self): + """This method is here if you want to add a resource listener to check + the status of resources loading.""" + pass + + def _createWorld ( self ): + """ this should be overridden when supporting the OgreRefApp framework. Also note you + will have to override __createCamera""" + pass + + def _loadResources(self): + """This loads all initial resources. Redefine this if you do not want + to load all resources at startup.""" + ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups() + + def _configure(self): + """This shows the config dialog and creates the renderWindow.""" + carryOn = self.root.showConfigDialog() + if carryOn: + self.renderWindow = self.root.initialise(True, "OGRE Render Window") + return carryOn + + def _chooseSceneManager(self): + """Chooses a default SceneManager.""" + #typedef uint16 SceneTypeMask; + #md=ogre.SceneManagerMetaData() + #md.sceneTypeMask=ogre.ST_GENERIC + #print dir(self.root) + self.sceneManager = self.root.createSceneManager(ogre.ST_GENERIC,"ExampleSMInstance") + + def _createCamera(self): + """Creates the camera.""" + self.camera = self.sceneManager.createCamera('PlayerCam') + self.camera.setPosition(ogre.Vector3(0, 0, 500)) + self.camera.lookAt(ogre.Vector3(0, 0, -300)) + self.camera.NearClipDistance = 5 + + def _createViewports(self): + """Creates the Viewport.""" + ## We want a single sampleframework so this work around is to support OgreRefApp Framework + ## if using the RefApp camera is based upon World etc etc + try: + self.viewport = self.renderWindow.addViewport(self.camera.getRealCamera()) + except AttributeError: + self.viewport = self.renderWindow.addViewport(self.camera) + self.viewport.BackgroundColour = ogre.ColourValue(0,0,0) + + def _createScene(self): + """Creates the scene. Override this with initial scene contents.""" + pass + + def _createFrameListener(self): + """Creates the FrameListener.""" + #,self.frameListener, self.frameListener.Mouse + self.frameListener = FrameListener(self.renderWindow, self.camera) + self.frameListener.showDebugOverlay(True) + self.root.addFrameListener(self.frameListener) + + def _isPsycoEnabled(self): + """Override this function and return True to turn on Psyco""" + return False + + def _activatePsyco(self): + """Import Psyco if available""" + try: + import psyco + psyco.full() + except ImportError: + pass + + +class FrameListener(ogre.FrameListener, ogre.WindowEventListener): + """A default frame listener, which takes care of basic mouse and keyboard + input.""" + + def __init__(self, renderWindow, camera, bufferedKeys = False, bufferedMouse = True, bufferedJoy = False): + ogre.FrameListener.__init__(self) + ogre.WindowEventListener.__init__(self) + self.camera = camera + self.renderWindow = renderWindow + self.statisticsOn = True + self.numScreenShots = 0 + self.timeUntilNextToggle = 0 + self.sceneDetailIndex = 0 + self.moveScale = 0.0 + self.rotationScale = 0.0 + self.translateVector = ogre.Vector3(0.0,0.0,0.0) + self.filtering = ogre.TFO_BILINEAR + self.showDebugOverlay(True) + self.moveSpeed = 100.0 + self.rotationSpeed = 8.0 + self.displayCameraDetails = False + self.bufferedKeys = bufferedKeys + self.bufferedMouse = bufferedMouse + self.bufferedJoy = bufferedJoy + self.MenuMode = False # lets understand a simple menu function + ## we can tell if we are using OgreRefapp based upon the camera class + + if self.camera.__class__ == ogre.Camera: + self.RefAppEnable = False + else: + self.RefAppEnable = True + self._setupInput() + + def __del__ (self ): + ogre.WindowEventUtilities.removeWindowEventListener(self.renderWindow, self) + self.windowClosed(self.renderWindow) + + def _setupInput(self): + # ignore buffered input + + windowHnd = self.renderWindow.getCustomAttributeInt("WINDOW") + self.InputManager = \ + OIS.createPythonInputSystem([("WINDOW",str(windowHnd))]) + + #pl = OIS.ParamList() + #windowHndStr = str ( windowHnd) + #pl.insert("WINDOW", windowHndStr) + #im = OIS.InputManager.createInputSystem( pl ) + + #Create all devices (We only catch joystick exceptions here, as, most people have Key/Mouse) + self.Keyboard = self.InputManager.createInputObjectKeyboard( OIS.OISKeyboard, self.bufferedKeys ) + self.Mouse = self.InputManager.createInputObjectMouse( OIS.OISMouse, self.bufferedMouse ) + try : + self.Joy = self.InputManager.createInputObjectJoyStick( OIS.OISJoyStick, bufferedJoy ) + except: + self.Joy = False + + #Set initial mouse clipping size + self.windowResized(self.renderWindow) + + self.showDebugOverlay(True) + + #Register as a Window listener + ogre.WindowEventUtilities.addWindowEventListener(self.renderWindow, self); + + def setMenuMode(self, mode): + self.MenuMode = mode + + def _UpdateSimulation( self, frameEvent ): + # create a real version of this to update the simulation + pass + + def windowResized (self, rw): + [width, height, depth, left, top] = rw.getMetrics() # Note the wrapped function as default needs unsigned int's + ms = self.Mouse.getMouseState() + ms.width = width + ms.height = height + + def windowClosed(self, rw): + #Only close for window that created OIS (mWindow) + if( rw == self.renderWindow ): + if( self.InputManager ): + self.InputManager.destroyInputObjectMouse( self.Mouse ) + self.InputManager.destroyInputObjectKeyboard( self.Keyboard ) + if self.Joy: + self.InputManager.destroyInputObjectJoyStick( self.Joy ) + OIS.InputManager.destroyInputSystem(self.InputManager) + self.InputManager=None + + def frameStarted(self, frameEvent): + if(self.renderWindow.isClosed()): + return False + + ##Need to capture/update each device - this will also trigger any listeners + self.Keyboard.capture() + self.Mouse.capture() + if( self.Joy ): + self.Joy.capture() + + ##bool buffJ = (mJoy) ? mJoy->buffered() : true; + + if self.timeUntilNextToggle >= 0: + self.timeUntilNextToggle -= frameEvent.timeSinceLastFrame + + if frameEvent.timeSinceLastFrame == 0: + self.moveScale = 1 + self.rotationScale = 0.1 + else: + self.moveScale = self.moveSpeed * frameEvent.timeSinceLastFrame + self.rotationScale = self.rotationSpeed * frameEvent.timeSinceLastFrame + + self.rotationX = ogre.Degree(0.0) + self.rotationY = ogre.Degree(0.0) + self.translateVector = ogre.Vector3(0.0, 0.0, 0.0) + if not self._processUnbufferedKeyInput(frameEvent): + return False + + if not self.MenuMode: # if we are in Menu mode we don't move the camera.. + self._processUnbufferedMouseInput(frameEvent) + + self._moveCamera() + # Perform simulation step only if using OgreRefApp. For simplicity create a function that simply does + ### "OgreRefApp.World.getSingleton().simulationStep(frameEvent.timeSinceLastFrame)" + + if self.RefAppEnable: + self._UpdateSimulation( frameEvent ) + return True + + def frameEnded(self, frameEvent): + self._updateStatistics() + return True + + def showDebugOverlay(self, show): + """Turns the debug overlay (frame statistics) on or off.""" + overlay = ogre.OverlayManager.getSingleton().getByName('Core/DebugOverlay') + if overlay is None: + raise ogre.Exception(111, "Could not find overlay Core/DebugOverlay", "SampleFramework.py") + if show: + overlay.show() + else: + overlay.hide() + + def _processUnbufferedKeyInput(self, frameEvent): + if self.Keyboard.isKeyDown(OIS.KC_A): + self.translateVector.x = -self.moveScale + + if self.Keyboard.isKeyDown(OIS.KC_D): + self.translateVector.x = self.moveScale + + if self.Keyboard.isKeyDown(OIS.KC_UP) or self.Keyboard.isKeyDown(OIS.KC_W): + self.translateVector.z = -self.moveScale + + if self.Keyboard.isKeyDown(OIS.KC_DOWN) or self.Keyboard.isKeyDown(OIS.KC_S): + self.translateVector.z = self.moveScale + + if self.Keyboard.isKeyDown(OIS.KC_PGUP): + self.translateVector.y = self.moveScale + + if self.Keyboard.isKeyDown(OIS.KC_PGDOWN): + self.translateVector.y = - self.moveScale + + if self.Keyboard.isKeyDown(OIS.KC_RIGHT): + self.rotationX = - self.rotationScale + + if self.Keyboard.isKeyDown(OIS.KC_LEFT): + self.rotationX = self.rotationScale + + if self.Keyboard.isKeyDown(OIS.KC_ESCAPE) or self.Keyboard.isKeyDown(OIS.KC_Q): + return False + + if( self.Keyboard.isKeyDown(OIS.KC_F) and self.timeUntilNextToggle <= 0 ): + self.statisticsOn = not self.statisticsOn + self.showDebugOverlay(self.statisticsOn) + self.timeUntilNextToggle = 1 + + if self.Keyboard.isKeyDown(OIS.KC_T) and self.timeUntilNextToggle <= 0: + if self.filtering == ogre.TFO_BILINEAR: + self.filtering = ogre.TFO_TRILINEAR + self.Aniso = 1 + elif self.filtering == ogre.TFO_TRILINEAR: + self.filtering = ogre.TFO_ANISOTROPIC + self.Aniso = 8 + else: + self.filtering = ogre.TFO_BILINEAR + self.Aniso = 1 + + ogre.MaterialManager.getSingleton().setDefaultTextureFiltering(self.filtering) + ogre.MaterialManager.getSingleton().setDefaultAnisotropy(self.Aniso) + self.showDebugOverlay(self.statisticsOn) + self.timeUntilNextToggle = 1 + + if self.Keyboard.isKeyDown(OIS.KC_SYSRQ) and self.timeUntilNextToggle <= 0: + path = 'screenshot_%d.png' % self.numScreenShots + self.numScreenShots += 1 + self.renderWindow.writeContentsToFile(path) + Application.debugText = 'screenshot taken: ' + path + self.timeUntilNextToggle = 0.5 + + if self.Keyboard.isKeyDown(OIS.KC_R) and self.timeUntilNextToggle <= 0: + detailsLevel = [ ogre.PM_SOLID, + ogre.PM_WIREFRAME, + ogre.PM_POINTS ] + self.sceneDetailIndex = (self.sceneDetailIndex + 1) % len(detailsLevel) + self.camera.polygonMode=detailsLevel[self.sceneDetailIndex] + self.timeUntilNextToggle = 0.5 + + if self.Keyboard.isKeyDown(OIS.KC_F) and self.timeUntilNextToggle <= 0: + self.statisticsOn = not self.statisticsOn + self.showDebugOverlay(self.statisticsOn) + self.timeUntilNextToggle = 1 + + if self.Keyboard.isKeyDown(OIS.KC_P) and self.timeUntilNextToggle <= 0: + self.displayCameraDetails = not self.displayCameraDetails + if not self.displayCameraDetails: + Application.debugText = "" + + if self.displayCameraDetails: + # Print camera details + pos = self.camera.getDerivedPosition() + o = self.camera.getDerivedOrientation() + Application.debugText = "P: %.3f %.3f %.3f O: %.3f %.3f %.3f %.3f" \ + % (pos.x,pos.y,pos.z, o.w,o.x,o.y,o.z) + return True + + def _isToggleKeyDown(self, keyCode, toggleTime = 1.0): + if self.Keyboard.isKeyDown(keyCode)and self.timeUntilNextToggle <=0: + self.timeUntilNextToggle = toggleTime + return True + return False + + def _isToggleMouseDown(self, Button, toggleTime = 1.0): + ms = self.Mouse.getMouseState() + if ms.buttonDown( Button ) and self.timeUntilNextToggle <=0: + self.timeUntilNextToggle = toggleTime + return True + return False + + def _processUnbufferedMouseInput(self, frameEvent): + ms = self.Mouse.getMouseState() + if ms.buttonDown( OIS.MB_Right ): + self.translateVector.x += ms.X.rel * 0.13 + self.translateVector.y -= ms.Y.rel * 0.13 + else: + self.rotationX = ogre.Degree(- ms.X.rel * 0.13) + self.rotationY = ogre.Degree(- ms.Y.rel * 0.13) + + def _moveCamera(self): + self.camera.yaw(self.rotationX) + self.camera.pitch(self.rotationY) + try: + self.camera.translate(self.translateVector) # for using OgreRefApp + except AttributeError: + self.camera.moveRelative(self.translateVector) + + def _updateStatistics(self): + statistics = self.renderWindow + self._setGuiCaption('Core/AverageFps', 'Average FPS: %f' % statistics.getAverageFPS()) + self._setGuiCaption('Core/CurrFps', 'Current FPS: %f' % statistics.getLastFPS()) + self._setGuiCaption('Core/BestFps', + 'Best FPS: %f %d ms' % (statistics.getBestFPS(), statistics.getBestFrameTime())) + self._setGuiCaption('Core/WorstFps', + 'Worst FPS: %f %d ms' % (statistics.getWorstFPS(), statistics.getWorstFrameTime())) + self._setGuiCaption('Core/NumTris', 'Triangle Count: %d' % statistics.getTriangleCount()) + self._setGuiCaption('Core/DebugText', Application.debugText) + + def _setGuiCaption(self, elementName, text): + element = ogre.OverlayManager.getSingleton().getOverlayElement(elementName, False) + ##d=ogre.UTFString("hell0") + ##element.setCaption(d) + + #element.caption="hello" + + #element.setCaption("help") + element.setCaption(ogre.UTFString(text)) Added: trunk/lib/ogre/renderer/OGRE/sf_utils.py =================================================================== --- trunk/lib/ogre/renderer/OGRE/sf_utils.py (rev 0) +++ trunk/lib/ogre/renderer/OGRE/sf_utils.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1,21 @@ +## Common utilities for the sample framework... +## +def getPluginPath(): + """Return the absolute path to a valid plugins.cfg file.""" + import sys + import os + import os.path + + paths = [os.path.join(os.getcwd(), 'plugins.cfg'), + '/etc/OGRE/plugins.cfg', + os.path.join(os.path.dirname(os.path.abspath(__file__)), + 'plugins.cfg')] + for path in paths: + if os.path.exists(path): + return path + + sys.stderr.write("\n" + "** Warning: Unable to locate a suitable plugins.cfg file.\n" + "** Warning: Please check your ogre installation and copy a\n" + "** Warning: working plugins.cfg file to the current directory.\n\n") + raise ogre.Exception(0, "can't locate the 'plugins.cfg' file", "") Added: trunk/lib/ogre/renderer/__init__.py =================================================================== --- trunk/lib/ogre/renderer/__init__.py (rev 0) +++ trunk/lib/ogre/renderer/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1 @@ +#keep me \ No newline at end of file Added: trunk/lib/ogre/sound/OgreAL/OgreAL.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/sound/OgreAL/OgreAL.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/sound/OgreAL/OpenAL32.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/sound/OgreAL/OpenAL32.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/sound/OgreAL/__init__.py =================================================================== --- trunk/lib/ogre/sound/OgreAL/__init__.py (rev 0) +++ trunk/lib/ogre/sound/OgreAL/__init__.py 2007-06-22 22:12:29 UTC (rev 8) @@ -0,0 +1,6 @@ +import sys, os + +if sys.platform == 'win32': + os.environ['PATH'] += ';' + __path__[0] + +from _ogreal_ import * \ No newline at end of file Added: trunk/lib/ogre/sound/OgreAL/_ogreal_.pyd =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/sound/OgreAL/_ogreal_.pyd ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/sound/OgreAL/alut.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/sound/OgreAL/alut.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/sound/OgreAL/ogg.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/sound/OgreAL/ogg.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/sound/OgreAL/vorbis.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/sound/OgreAL/vorbis.dll ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/ogre/sound/OgreAL/vorbisfile.dll =================================================================== (Binary files differ) Property changes on: trunk/lib/ogre/sound/OgreAL/vorbisfile.dll _____________________________________________... [truncated message content] |
From: <ror...@us...> - 2007-06-23 14:42:03
|
Revision: 16 http://roreditor.svn.sourceforge.net/roreditor/?rev=16&view=rev Author: rorthomas Date: 2007-06-23 07:41:59 -0700 (Sat, 23 Jun 2007) Log Message: ----------- * added psyco to libs. * using psyco on startup * added documentation basics Modified Paths: -------------- trunk/lib/ror/starter.py trunk/lib/wxogre/wxOgreWindow.py trunk/ogre.cfg trunk/rortoolkit.py trunk/terraineditor.py trunk/truckeditor.py Added Paths: ----------- trunk/doc/ trunk/doc/createdoc.bat trunk/doc/createdoc.py trunk/doc/epydoc.conf trunk/lib/psyco/ trunk/lib/psyco/__init__.py trunk/lib/psyco/__init__.pyo trunk/lib/psyco/_psyco.pyd trunk/lib/psyco/classes.py trunk/lib/psyco/classes.pyo trunk/lib/psyco/core.py trunk/lib/psyco/core.pyo trunk/lib/psyco/kdictproxy.py trunk/lib/psyco/kdictproxy.pyo trunk/lib/psyco/logger.py trunk/lib/psyco/logger.pyo trunk/lib/psyco/profiler.py trunk/lib/psyco/profiler.pyo trunk/lib/psyco/support.py trunk/lib/psyco/support.pyo Added: trunk/doc/createdoc.bat =================================================================== --- trunk/doc/createdoc.bat (rev 0) +++ trunk/doc/createdoc.bat 2007-06-23 14:41:59 UTC (rev 16) @@ -0,0 +1 @@ +c:\python25\python.exe createdoc.py -vv --name RoRToolkit --url http://wiki.rigsofrods.com/index.php?title=Main_Page --debug psyco ogre ror rorterraineditor rortruckeditor wx wxogre \ No newline at end of file Added: trunk/doc/createdoc.py =================================================================== --- trunk/doc/createdoc.py (rev 0) +++ trunk/doc/createdoc.py 2007-06-23 14:41:59 UTC (rev 16) @@ -0,0 +1,25 @@ +#Thomas Fischer 31/05/2007, th...@th... +import sys, os, os.path + +def main(): + """ + main method + """ + + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..\lib")) + + # Import Psyco if available + try: + import psyco + psyco.full() + #psyco.log() + #psyco.profile() + except ImportError: + pass + + import epydoc.cli + epydoc.cli.cli() + + +if __name__=="__main__": + main() \ No newline at end of file Added: trunk/doc/epydoc.conf =================================================================== --- trunk/doc/epydoc.conf (rev 0) +++ trunk/doc/epydoc.conf 2007-06-23 14:41:59 UTC (rev 16) @@ -0,0 +1,148 @@ +[epydoc] + +# The list of objects to document. Objects can be named using +# dotted names, module filenames, or package directory names. +# Alases for this option include "objects" and "values". +modules: psyco + +# The type of output that should be generated. Should be one +# of: html, text, latex, dvi, ps, pdf. +output: html + +# The path to the output directory. May be relative or absolute. +target: html/ + +# An integer indicating how verbose epydoc should be. The default +# value is 0; negative values will supress warnings and errors; +# positive values will give more verbose output. +verbosity: 3 + +# A boolean value indicating that Epydoc should show a tracaback +# in case of unexpected error. By default don't show tracebacks +debug: 1 + +# If True, don't try to use colors or cursor control when doing +# textual output. The default False assumes a rich text prompt +simple-term: 0 + + +### Generation options + +# The default markup language for docstrings, for modules that do +# not define __docformat__. Defaults to epytext. +docformat: epytext + +# Whether or not parsing should be used to examine objects. +parse: yes + +# Whether or not introspection should be used to examine objects. +introspect: yes + +# Don't examine in any way the modules whose dotted name match this +# regular expression pattern. +#exclude + +# Don't perform introspection on the modules whose dotted name match this +# regular expression pattern. +#exclude-introspect + +# Don't perform parsing on the modules whose dotted name match this +# regular expression pattern. +#exclude-parse + +# The format for showing inheritance objects. +# It should be one of: 'grouped', 'listed', 'included'. +inheritance: listed + +# Whether or not to inclue private variables. (Even if included, +# private variables will be hidden by default.) +private: yes + +# Whether or not to list each module's imports. +imports: no + +# Whether or not to include syntax highlighted source code in +# the output (HTML only). +sourcecode: yes + +# Whether or not to includea a page with Epydoc log, containing +# effective option at the time of generation and the reported logs. +include-log: yes + + +### Output options + +# The documented project's name. +name: RoRToolkit + +# The CSS stylesheet for HTML output. Can be the name of a builtin +# stylesheet, or the name of a file. +css: white + +# The documented project's URL. +url: http://wiki.rigsofrods.com/index.php?title=Main_Page + +# HTML code for the project link in the navigation bar. If left +# unspecified, the project link will be generated based on the +# project's name and URL. +#link: <a href="somewhere">My Cool Project</a> + +# The "top" page for the documentation. Can be a URL, the name +# of a module or class, or one of the special names "trees.html", +# "indices.html", or "help.html" +#top: os.path + +# An alternative help file. The named file should contain the +# body of an HTML file; navigation bars will be added to it. +#help: my_helpfile.html + +# Whether or not to include a frames-based table of contents. +frames: yes + +# Whether each class should be listed in its own section when +# generating LaTeX or PDF output. +separate-classes: no + + +### API linking options + +# Define a new API document. A new interpreted text role +# will be created +#external-api: epydoc + +# Use the records in this file to resolve objects in the API named NAME. +#external-api-file: epydoc:api-objects.txt + +# Use this URL prefix to configure the string returned for external API. +#external-api-root: epydoc:http://epydoc.sourceforge.net/api + + +### Graph options + +# The list of graph types that should be automatically included +# in the output. Graphs are generated using the Graphviz "dot" +# executable. Graph types include: "classtree", "callgraph", +# "umlclass". Use "all" to include all graph types +graph: all + +# The path to the Graphviz "dot" executable, used to generate +# graphs. +dotpath: C:\Programme\ATT\Graphviz\bin\dot.exe + +# The name of one or more pstat files (generated by the profile +# or hotshot module). These are used to generate call graphs. +pstat: profile.out + +# Specify the font used to generate Graphviz graphs. +# (e.g., helvetica or times). +graph-font: Helvetica + +# Specify the font size used to generate Graphviz graphs. +graph-font-size: 10 + + +### Return value options + +# The condition upon which Epydoc should exit with a non-zero +# exit status. Possible values are error, warning, docstring_warning +#fail-on: error Added: trunk/lib/psyco/__init__.py =================================================================== --- trunk/lib/psyco/__init__.py (rev 0) +++ trunk/lib/psyco/__init__.py 2007-06-23 14:41:59 UTC (rev 16) @@ -0,0 +1,58 @@ +########################################################################### +# +# Psyco top-level file of the Psyco package. +# Copyright (C) 2001-2002 Armin Rigo et.al. + +"""Psyco -- the Python Specializing Compiler. + +Typical usage: add the following lines to your application's main module, +preferably after the other imports: + +try: + import psyco + psyco.full() +except ImportError: + print 'Psyco not installed, the program will just run slower' +""" +########################################################################### + + +# +# This module is present to make 'psyco' a package and to +# publish the main functions and variables. +# +# More documentation can be found in core.py. +# + + +# Try to import the dynamic-loading _psyco and report errors +try: + import _psyco +except ImportError, e: + extramsg = '' + import sys, imp + try: + file, filename, (suffix, mode, type) = imp.find_module('_psyco', __path__) + except ImportError: + ext = [suffix for suffix, mode, type in imp.get_suffixes() + if type == imp.C_EXTENSION] + if ext: + extramsg = (" (cannot locate the compiled extension '_psyco%s' " + "in the package path '%s')" % (ext[0], '; '.join(__path__))) + else: + extramsg = (" (check that the compiled extension '%s' is for " + "the correct Python version; this is Python %s)" % + (filename, sys.version.split()[0])) + raise ImportError, str(e) + extramsg + +# Publish important data by importing them in the package +from support import __version__, error, warning, _getrealframe, _getemulframe +from support import version_info, __version__ as hexversion +from core import full, profile, background, runonly, stop, cannotcompile +from core import log, bind, unbind, proxy, unproxy, dumpcodebuf +from _psyco import setfilter + +try: + from _psyco import compact, compacttype # Python 2.2 and above only +except ImportError: + pass Added: trunk/lib/psyco/__init__.pyo =================================================================== (Binary files differ) Property changes on: trunk/lib/psyco/__init__.pyo ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/psyco/_psyco.pyd =================================================================== (Binary files differ) Property changes on: trunk/lib/psyco/_psyco.pyd ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/psyco/classes.py =================================================================== --- trunk/lib/psyco/classes.py (rev 0) +++ trunk/lib/psyco/classes.py 2007-06-23 14:41:59 UTC (rev 16) @@ -0,0 +1,53 @@ +########################################################################### +# +# Psyco class support module. +# Copyright (C) 2001-2002 Armin Rigo et.al. + +"""Psyco class support module. + +'psyco.classes.psyobj' is an alternate Psyco-optimized root for classes. +Any class inheriting from it or using the metaclass '__metaclass__' might +get optimized specifically for Psyco. It is equivalent to call +psyco.bind() on the class object after its creation. + +Note that this module has no effect with Python version 2.1 or earlier. + +Importing everything from psyco.classes in a module will import the +'__metaclass__' name, so all classes defined after a + + from psyco.classes import * + +will automatically use the Psyco-optimized metaclass. +""" +########################################################################### + +__all__ = ['psyobj', 'psymetaclass', '__metaclass__'] + + +# Python version check +try: + from _psyco import compacttype +except ImportError: + class psyobj: # compatilibity + pass + psymetaclass = None +else: + # version >= 2.2 only + + import core + from types import FunctionType + + class psymetaclass(compacttype): + "Psyco-optimized meta-class. Turns all methods into Psyco proxies." + + def __new__(cls, name, bases, dict): + bindlist = dict.get('__psyco__bind__') + if bindlist is None: + bindlist = [key for key, value in dict.items() + if isinstance(value, FunctionType)] + for attr in bindlist: + dict[attr] = core.proxy(dict[attr]) + return super(psymetaclass, cls).__new__(cls, name, bases, dict) + + psyobj = psymetaclass("psyobj", (), {}) +__metaclass__ = psymetaclass Added: trunk/lib/psyco/classes.pyo =================================================================== (Binary files differ) Property changes on: trunk/lib/psyco/classes.pyo ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/psyco/core.py =================================================================== --- trunk/lib/psyco/core.py (rev 0) +++ trunk/lib/psyco/core.py 2007-06-23 14:41:59 UTC (rev 16) @@ -0,0 +1,232 @@ +########################################################################### +# +# Psyco main functions. +# Copyright (C) 2001-2002 Armin Rigo et.al. + +"""Psyco main functions. + +Here are the routines that you can use from your applications. +These are mostly interfaces to the C core, but they depend on +the Python version. + +You can use these functions from the 'psyco' module instead of +'psyco.core', e.g. + + import psyco + psyco.log('/tmp/psyco.log') + psyco.profile() +""" +########################################################################### + +import _psyco +import types, new +from support import * + + +# Default charge profiler values +default_watermark = 0.09 # between 0.0 (0%) and 1.0 (100%) +default_halflife = 0.5 # seconds +default_pollfreq_profile = 20 # Hz +default_pollfreq_background = 100 # Hz -- a maximum for sleep's resolution +default_parentframe = 0.25 # should not be more than 0.5 (50%) + + +def full(memory=None, time=None, memorymax=None, timemax=None): + """Compile as much as possible. + +Typical use is for small scripts performing intensive computations +or string handling.""" + import profiler + if PYTHON_SUPPORT: + p = profiler.FullCompiler() + else: + p = profiler.ActiveProfiler(0.0, 0.5) + p.run(memory, time, memorymax, timemax) + + +def profile(watermark = default_watermark, + halflife = default_halflife, + pollfreq = default_pollfreq_profile, + parentframe = default_parentframe, + memory=None, time=None, memorymax=None, timemax=None): + """Turn on profiling. + +The 'watermark' parameter controls how easily running functions will +be compiled. The smaller the value, the more functions are compiled.""" + import profiler + p = profiler.ActivePassiveProfiler(watermark, halflife, + pollfreq, parentframe) + p.run(memory, time, memorymax, timemax) + + +def background(watermark = default_watermark, + halflife = default_halflife, + pollfreq = default_pollfreq_background, + parentframe = default_parentframe, + memory=None, time=None, memorymax=None, timemax=None): + """Turn on passive profiling. + +This is a very lightweight mode in which only intensively computing +functions can be detected. The smaller the 'watermark', the more functions +are compiled.""" + import profiler + p = profiler.PassiveProfiler(watermark, halflife, pollfreq, parentframe) + p.run(memory, time, memorymax, timemax) + + +def runonly(memory=None, time=None, memorymax=None, timemax=None): + """Nonprofiler. + +XXX check if this is useful and document.""" + if PYTHON_SUPPORT: + import profiler + p = profiler.RunOnly() + p.run(memory, time, memorymax, timemax) + + +def stop(): + """Turn off all automatic compilation. bind() calls remain in effect.""" + import profiler + profiler.go([]) + + +def log(logfile='', mode='w', top=10): + """Enable logging to the given file. + +If the file name is unspecified, a default name is built by appending +a 'log-psyco' extension to the main script name. + +Mode is 'a' to append to a possibly existing file or 'w' to overwrite +an existing file. Note that the log file may grow quickly in 'a' mode.""" + import profiler, logger + if not logfile: + import os + logfile, dummy = os.path.splitext(sys.argv[0]) + if os.path.basename(logfile): + logfile += '.' + logfile += 'log-psyco' + if hasattr(_psyco, 'VERBOSE_LEVEL'): + print >> sys.stderr, 'psyco: logging to', logfile + # logger.current should be a real file object; subtle problems + # will show up if its write() and flush() methods are written + # in Python, as Psyco will invoke them while compiling. + logger.current = open(logfile, mode) + logger.print_charges = top + profiler.logger = logger + logger.writedate('Logging started') + cannotcompile(logger.psycowrite) + _psyco.statwrite(logger=logger.psycowrite) + + +def bind(x, rec=None): + """Enable compilation of the given function, method, or class object. + +If C is a class (or anything with a '__dict__' attribute), bind(C) will +rebind all functions and methods found in C.__dict__ (which means, for +classes, all methods defined in the class but not in its parents). + +The optional second argument specifies the number of recursive +compilation levels: all functions called by func are compiled +up to the given depth of indirection.""" + if isinstance(x, types.MethodType): + x = x.im_func + if isinstance(x, types.FunctionType): + if rec is None: + x.func_code = _psyco.proxycode(x) + else: + x.func_code = _psyco.proxycode(x, rec) + return + if hasattr(x, '__dict__'): + funcs = [o for o in x.__dict__.values() + if isinstance(o, types.MethodType) + or isinstance(o, types.FunctionType)] + if not funcs: + raise error, ("nothing bindable found in %s object" % + type(x).__name__) + for o in funcs: + bind(o, rec) + return + raise TypeError, "cannot bind %s objects" % type(x).__name__ + + +def unbind(x): + """Reverse of bind().""" + if isinstance(x, types.MethodType): + x = x.im_func + if isinstance(x, types.FunctionType): + try: + f = _psyco.unproxycode(x.func_code) + except error: + pass + else: + x.func_code = f.func_code + return + if hasattr(x, '__dict__'): + for o in x.__dict__.values(): + if (isinstance(o, types.MethodType) + or isinstance(o, types.FunctionType)): + unbind(o) + return + raise TypeError, "cannot unbind %s objects" % type(x).__name__ + + +def proxy(x, rec=None): + """Return a Psyco-enabled copy of the function. + +The original function is still available for non-compiled calls. +The optional second argument specifies the number of recursive +compilation levels: all functions called by func are compiled +up to the given depth of indirection.""" + if isinstance(x, types.FunctionType): + if rec is None: + code = _psyco.proxycode(x) + else: + code = _psyco.proxycode(x, rec) + return new.function(code, x.func_globals, x.func_name) + if isinstance(x, types.MethodType): + p = proxy(x.im_func, rec) + return new.instancemethod(p, x.im_self, x.im_class) + raise TypeError, "cannot proxy %s objects" % type(x).__name__ + + +def unproxy(proxy): + """Return a new copy of the original function of method behind a proxy. +The result behaves like the original function in that calling it +does not trigger compilation nor execution of any compiled code.""" + if isinstance(proxy, types.FunctionType): + return _psyco.unproxycode(proxy.func_code) + if isinstance(proxy, types.MethodType): + f = unproxy(proxy.im_func) + return new.instancemethod(f, proxy.im_self, proxy.im_class) + raise TypeError, "%s objects cannot be proxies" % type(proxy).__name__ + + +def cannotcompile(x): + """Instruct Psyco never to compile the given function, method +or code object.""" + if isinstance(x, types.MethodType): + x = x.im_func + if isinstance(x, types.FunctionType): + x = x.func_code + if isinstance(x, types.CodeType): + _psyco.cannotcompile(x) + else: + raise TypeError, "unexpected %s object" % type(x).__name__ + + +def dumpcodebuf(): + """Write in file psyco.dump a copy of the emitted machine code, +provided Psyco was compiled with a non-zero CODE_DUMP. +See py-utils/httpxam.py to examine psyco.dump.""" + if hasattr(_psyco, 'dumpcodebuf'): + _psyco.dumpcodebuf() + + +########################################################################### +# Psyco variables +# error * the error raised by Psyco +# warning * the warning raised by Psyco +# __in_psyco__ * a new built-in variable which is always zero, but which +# Psyco special-cases by returning 1 instead. So +# __in_psyco__ can be used in a function to know if +# that function is being executed by Psyco or not. Added: trunk/lib/psyco/core.pyo =================================================================== (Binary files differ) Property changes on: trunk/lib/psyco/core.pyo ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/psyco/kdictproxy.py =================================================================== --- trunk/lib/psyco/kdictproxy.py (rev 0) +++ trunk/lib/psyco/kdictproxy.py 2007-06-23 14:41:59 UTC (rev 16) @@ -0,0 +1,133 @@ +########################################################################### +# +# Support code for the 'psyco.compact' type. + +from __future__ import generators + +try: + from UserDict import DictMixin +except ImportError: + + # backported from Python 2.3 to Python 2.2 + class DictMixin: + # Mixin defining all dictionary methods for classes that already have + # a minimum dictionary interface including getitem, setitem, delitem, + # and keys. Without knowledge of the subclass constructor, the mixin + # does not define __init__() or copy(). In addition to the four base + # methods, progressively more efficiency comes with defining + # __contains__(), __iter__(), and iteritems(). + + # second level definitions support higher levels + def __iter__(self): + for k in self.keys(): + yield k + def has_key(self, key): + try: + value = self[key] + except KeyError: + return False + return True + def __contains__(self, key): + return self.has_key(key) + + # third level takes advantage of second level definitions + def iteritems(self): + for k in self: + yield (k, self[k]) + def iterkeys(self): + return self.__iter__() + + # fourth level uses definitions from lower levels + def itervalues(self): + for _, v in self.iteritems(): + yield v + def values(self): + return [v for _, v in self.iteritems()] + def items(self): + return list(self.iteritems()) + def clear(self): + for key in self.keys(): + del self[key] + def setdefault(self, key, default): + try: + return self[key] + except KeyError: + self[key] = default + return default + def pop(self, key, *args): + if len(args) > 1: + raise TypeError, "pop expected at most 2 arguments, got "\ + + repr(1 + len(args)) + try: + value = self[key] + except KeyError: + if args: + return args[0] + raise + del self[key] + return value + def popitem(self): + try: + k, v = self.iteritems().next() + except StopIteration: + raise KeyError, 'container is empty' + del self[k] + return (k, v) + def update(self, other): + # Make progressively weaker assumptions about "other" + if hasattr(other, 'iteritems'): # iteritems saves memory and lookups + for k, v in other.iteritems(): + self[k] = v + elif hasattr(other, '__iter__'): # iter saves memory + for k in other: + self[k] = other[k] + else: + for k in other.keys(): + self[k] = other[k] + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default + def __repr__(self): + return repr(dict(self.iteritems())) + def __cmp__(self, other): + if other is None: + return 1 + if isinstance(other, DictMixin): + other = dict(other.iteritems()) + return cmp(dict(self.iteritems()), other) + def __len__(self): + return len(self.keys()) + +########################################################################### + +from _psyco import compact # Python 2.2 and above only + + +class compactdictproxy(DictMixin): + + def __init__(self, ko): + self._ko = ko # compact object of which 'self' is the dict + + def __getitem__(self, key): + return compact.__getslot__(self._ko, key) + + def __setitem__(self, key, value): + compact.__setslot__(self._ko, key, value) + + def __delitem__(self, key): + compact.__delslot__(self._ko, key) + + def keys(self): + return compact.__members__.__get__(self._ko) + + def clear(self): + keys = self.keys() + keys.reverse() + for key in keys: + del self[key] + + def __repr__(self): + keys = ', '.join(self.keys()) + return '<compactdictproxy object {%s}>' % (keys,) Added: trunk/lib/psyco/kdictproxy.pyo =================================================================== (Binary files differ) Property changes on: trunk/lib/psyco/kdictproxy.pyo ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/psyco/logger.py =================================================================== --- trunk/lib/psyco/logger.py (rev 0) +++ trunk/lib/psyco/logger.py 2007-06-23 14:41:59 UTC (rev 16) @@ -0,0 +1,96 @@ +########################################################################### +# +# Psyco logger. +# Copyright (C) 2001-2002 Armin Rigo et.al. + +"""Psyco logger. + +See log() in core.py. +""" +########################################################################### + + +import _psyco +from time import time, localtime, strftime + + +current = None +print_charges = 10 +dump_delay = 0.2 +dump_last = 0.0 + +def write(s, level): + t = time() + f = t-int(t) + try: + current.write("%s.%02d %-*s%s\n" % ( + strftime("%X", localtime(int(t))), + int(f*100.0), 63-level, s, + "%"*level)) + current.flush() + except (OSError, IOError): + pass + +def psycowrite(s): + t = time() + f = t-int(t) + try: + current.write("%s.%02d %-*s%s\n" % ( + strftime("%X", localtime(int(t))), + int(f*100.0), 60, s.strip(), + "% %")) + current.flush() + except (OSError, IOError): + pass + +##def writelines(lines, level=0): +## if lines: +## t = time() +## f = t-int(t) +## timedesc = strftime("%x %X", localtime(int(t))) +## print >> current, "%s.%03d %-*s %s" % ( +## timedesc, int(f*1000), +## 50-level, lines[0], +## "+"*level) +## timedesc = " " * (len(timedesc)+5) +## for line in lines[1:]: +## print >> current, timedesc, line + +def writememory(): + write("memory usage: %d+ kb" % _psyco.memory(), 1) + +def dumpcharges(): + global dump_last + if print_charges: + t = time() + if not (dump_last <= t < dump_last+dump_delay): + if t <= dump_last+1.5*dump_delay: + dump_last += dump_delay + else: + dump_last = t + #write("%s: charges:" % who, 0) + lst = _psyco.stattop(print_charges) + if lst: + f = t-int(t) + lines = ["%s.%02d ______\n" % ( + strftime("%X", localtime(int(t))), + int(f*100.0))] + i = 1 + for co, charge in lst: + detail = co.co_filename + if len(detail) > 19: + detail = '...' + detail[-17:] + lines.append(" #%-3d |%4.1f %%| %-26s%20s:%d\n" % + (i, charge*100.0, co.co_name, detail, + co.co_firstlineno)) + i += 1 + current.writelines(lines) + current.flush() + +def writefinalstats(): + dumpcharges() + writememory() + writedate("program exit") + +def writedate(msg): + write('%s, %s' % (msg, strftime("%x")), 20) Added: trunk/lib/psyco/logger.pyo =================================================================== (Binary files differ) Property changes on: trunk/lib/psyco/logger.pyo ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/psyco/profiler.py =================================================================== --- trunk/lib/psyco/profiler.py (rev 0) +++ trunk/lib/psyco/profiler.py 2007-06-23 14:41:59 UTC (rev 16) @@ -0,0 +1,388 @@ +########################################################################### +# +# Psyco profiler (Python part). +# Copyright (C) 2001-2002 Armin Rigo et.al. + +"""Psyco profiler (Python part). + +The implementation of the non-time-critical parts of the profiler. +See profile() and full() in core.py for the easy interface. +""" +########################################################################### + +import _psyco +from support import * +import math, time, types, atexit +now = time.time +try: + import thread +except ImportError: + import dummy_thread as thread + + +# current profiler instance +current = None + +# enabled profilers, in order of priority +profilers = [] + +# logger module (when enabled by core.log()) +logger = None + +# a lock for a thread-safe go() +go_lock = thread.allocate_lock() + +def go(stop=0): + # run the highest-priority profiler in 'profilers' + global current + go_lock.acquire() + try: + prev = current + if stop: + del profilers[:] + if prev: + if profilers and profilers[0] is prev: + return # best profiler already running + prev.stop() + current = None + for p in profilers[:]: + if p.start(): + current = p + if logger: # and p is not prev: + logger.write("%s: starting" % p.__class__.__name__, 5) + return + finally: + go_lock.release() + # no profiler is running now + if stop: + if logger: + logger.writefinalstats() + else: + tag2bind() + +atexit.register(go, 1) + + +def buildfncache(globals, cache): + if hasattr(types.IntType, '__dict__'): + clstypes = (types.ClassType, types.TypeType) + else: + clstypes = types.ClassType + for x in globals.values(): + if isinstance(x, types.MethodType): + x = x.im_func + if isinstance(x, types.FunctionType): + cache[x.func_code] = x, '' + elif isinstance(x, clstypes): + for y in x.__dict__.values(): + if isinstance(y, types.MethodType): + y = y.im_func + if isinstance(y, types.FunctionType): + cache[y.func_code] = y, x.__name__ + +# code-to-function mapping (cache) +function_cache = {} + +def trytobind(co, globals, log=1): + try: + f, clsname = function_cache[co] + except KeyError: + buildfncache(globals, function_cache) + try: + f, clsname = function_cache[co] + except KeyError: + if logger: + logger.write('warning: cannot find function %s in %s' % + (co.co_name, globals.get('__name__', '?')), 3) + return # give up + if logger and log: + modulename = globals.get('__name__', '?') + if clsname: + modulename += '.' + clsname + logger.write('bind function: %s.%s' % (modulename, co.co_name), 1) + f.func_code = _psyco.proxycode(f) + + +if PYTHON_SUPPORT: + # the list of code objects that have been tagged + tagged_codes = [] + + def tag(co, globals): + if logger: + try: + f, clsname = function_cache[co] + except KeyError: + buildfncache(globals, function_cache) + try: + f, clsname = function_cache[co] + except KeyError: + clsname = '' # give up + modulename = globals.get('__name__', '?') + if clsname: + modulename += '.' + clsname + logger.write('tag function: %s.%s' % (modulename, co.co_name), 1) + tagged_codes.append((co, globals)) + _psyco.turbo_frame(co) + _psyco.turbo_code(co) + + def tag2bind(): + if tagged_codes: + if logger: + logger.write('profiling stopped, binding %d functions' % + len(tagged_codes), 2) + for co, globals in tagged_codes: + trytobind(co, globals, 0) + function_cache.clear() + del tagged_codes[:] + +else: + # tagging is impossible, always bind + tag = trytobind + def tag2bind(): + pass + + + +class Profiler: + MemoryTimerResolution = 0.103 + + def run(self, memory, time, memorymax, timemax): + self.memory = memory + self.memorymax = memorymax + self.time = time + if timemax is None: + self.endtime = None + else: + self.endtime = now() + timemax + self.alarms = [] + profilers.append(self) + go() + + def start(self): + curmem = _psyco.memory() + memlimits = [] + if self.memorymax is not None: + if curmem >= self.memorymax: + if logger: + logger.writememory() + return self.limitreached('memorymax') + memlimits.append(self.memorymax) + if self.memory is not None: + if self.memory <= 0: + if logger: + logger.writememory() + return self.limitreached('memory') + memlimits.append(curmem + self.memory) + self.memory_at_start = curmem + + curtime = now() + timelimits = [] + if self.endtime is not None: + if curtime >= self.endtime: + return self.limitreached('timemax') + timelimits.append(self.endtime - curtime) + if self.time is not None: + if self.time <= 0.0: + return self.limitreached('time') + timelimits.append(self.time) + self.time_at_start = curtime + + try: + self.do_start() + except error, e: + if logger: + logger.write('%s: disabled by psyco.error:' % ( + self.__class__.__name__), 4) + logger.write(' %s' % str(e), 3) + return 0 + + if memlimits: + self.memlimits_args = (time.sleep, (self.MemoryTimerResolution,), + self.check_memory, (min(memlimits),)) + self.alarms.append(_psyco.alarm(*self.memlimits_args)) + if timelimits: + self.alarms.append(_psyco.alarm(time.sleep, (min(timelimits),), + self.time_out)) + return 1 + + def stop(self): + for alarm in self.alarms: + alarm.stop(0) + for alarm in self.alarms: + alarm.stop(1) # wait for parallel threads to stop + del self.alarms[:] + if self.time is not None: + self.time -= now() - self.time_at_start + if self.memory is not None: + self.memory -= _psyco.memory() - self.memory_at_start + + try: + self.do_stop() + except error: + return 0 + return 1 + + def check_memory(self, limit): + if _psyco.memory() < limit: + return self.memlimits_args + go() + + def time_out(self): + self.time = 0.0 + go() + + def limitreached(self, limitname): + try: + profilers.remove(self) + except ValueError: + pass + if logger: + logger.write('%s: disabled (%s limit reached)' % ( + self.__class__.__name__, limitname), 4) + return 0 + + +class FullCompiler(Profiler): + + def do_start(self): + _psyco.profiling('f') + + def do_stop(self): + _psyco.profiling('.') + + +class RunOnly(Profiler): + + def do_start(self): + _psyco.profiling('n') + + def do_stop(self): + _psyco.profiling('.') + + +class ChargeProfiler(Profiler): + + def __init__(self, watermark, parentframe): + self.watermark = watermark + self.parent2 = parentframe * 2.0 + self.lock = thread.allocate_lock() + + def init_charges(self): + _psyco.statwrite(watermark = self.watermark, + parent2 = self.parent2) + + def do_stop(self): + _psyco.profiling('.') + _psyco.statwrite(callback = None) + + +class ActiveProfiler(ChargeProfiler): + + def active_start(self): + _psyco.profiling('p') + + def do_start(self): + self.init_charges() + self.active_start() + _psyco.statwrite(callback = self.charge_callback) + + def charge_callback(self, frame, charge): + tag(frame.f_code, frame.f_globals) + + +class PassiveProfiler(ChargeProfiler): + + initial_charge_unit = _psyco.statread('unit') + reset_stats_after = 120 # half-lives (maximum 200!) + reset_limit = initial_charge_unit * (2.0 ** reset_stats_after) + + def __init__(self, watermark, halflife, pollfreq, parentframe): + ChargeProfiler.__init__(self, watermark, parentframe) + self.pollfreq = pollfreq + # self.progress is slightly more than 1.0, and computed so that + # do_profile() will double the change_unit every 'halflife' seconds. + self.progress = 2.0 ** (1.0 / (halflife * pollfreq)) + + def reset(self): + _psyco.statwrite(unit = self.initial_charge_unit, callback = None) + _psyco.statreset() + if logger: + logger.write("%s: resetting stats" % self.__class__.__name__, 1) + + def passive_start(self): + self.passivealarm_args = (time.sleep, (1.0 / self.pollfreq,), + self.do_profile) + self.alarms.append(_psyco.alarm(*self.passivealarm_args)) + + def do_start(self): + tag2bind() + self.init_charges() + self.passive_start() + + def do_profile(self): + _psyco.statcollect() + if logger: + logger.dumpcharges() + nunit = _psyco.statread('unit') * self.progress + if nunit > self.reset_limit: + self.reset() + else: + _psyco.statwrite(unit = nunit, callback = self.charge_callback) + return self.passivealarm_args + + def charge_callback(self, frame, charge): + trytobind(frame.f_code, frame.f_globals) + + +class ActivePassiveProfiler(PassiveProfiler, ActiveProfiler): + + def do_start(self): + self.init_charges() + self.active_start() + self.passive_start() + + def charge_callback(self, frame, charge): + tag(frame.f_code, frame.f_globals) + + + +# +# we register our own version of sys.settrace(), sys.setprofile() +# and thread.start_new_thread(). +# + +def psyco_settrace(*args, **kw): + "This is the Psyco-aware version of sys.settrace()." + result = original_settrace(*args, **kw) + go() + return result + +def psyco_setprofile(*args, **kw): + "This is the Psyco-aware version of sys.setprofile()." + result = original_setprofile(*args, **kw) + go() + return result + +def psyco_thread_stub(callable, args, kw): + _psyco.statcollect() + if kw is None: + return callable(*args) + else: + return callable(*args, **kw) + +def psyco_start_new_thread(callable, args, kw=None): + "This is the Psyco-aware version of thread.start_new_thread()." + return original_start_new_thread(psyco_thread_stub, (callable, args, kw)) + +original_settrace = sys.settrace +original_setprofile = sys.setprofile +original_start_new_thread = thread.start_new_thread +sys.settrace = psyco_settrace +sys.setprofile = psyco_setprofile +if PYTHON_SUPPORT: + thread.start_new_thread = psyco_start_new_thread + # hack to patch threading._start_new_thread if the module is + # already loaded + if (sys.modules.has_key('threading') and + hasattr(sys.modules['threading'], '_start_new_thread')): + sys.modules['threading']._start_new_thread = psyco_start_new_thread Added: trunk/lib/psyco/profiler.pyo =================================================================== (Binary files differ) Property changes on: trunk/lib/psyco/profiler.pyo ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: trunk/lib/psyco/support.py =================================================================== --- trunk/lib/psyco/support.py (rev 0) +++ trunk/lib/psyco/support.py 2007-06-23 14:41:59 UTC (rev 16) @@ -0,0 +1,196 @@ +########################################################################### +# +# Psyco general support module. +# Copyright (C) 2001-2002 Armin Rigo et.al. + +"""Psyco general support module. + +For internal use. +""" +########################################################################### + +import sys, _psyco, __builtin__ + +error = _psyco.error +class warning(Warning): + pass + +_psyco.NoLocalsWarning = warning + +def warn(msg): + from warnings import warn + warn(msg, warning, stacklevel=2) + +# +# Version checks +# +__version__ = 0x010502f0 +if _psyco.PSYVER != __version__: + raise error, "version mismatch between Psyco parts, reinstall it" + +version_info = (__version__ >> 24, + (__version__ >> 16) & 0xff, + (__version__ >> 8) & 0xff, + {0xa0: 'alpha', + 0xb0: 'beta', + 0xc0: 'candidate', + 0xf0: 'final'}[__version__ & 0xf0], + __version__ & 0xf) + + +VERSION_LIMITS = [0x02010000, # 2.1 + 0x02020000, # 2.2 + 0x02020200, # 2.2.2 + 0x02030000, # 2.3 + 0x02040000] # 2.4 + +if ([v for v in VERSION_LIMITS if v <= sys.hexversion] != + [v for v in VERSION_LIMITS if v <= _psyco.PYVER ]): + if sys.hexversion < VERSION_LIMITS[0]: + warn("Psyco requires Python version 2.1 or later") + else: + warn("Psyco version does not match Python version. " + "Psyco must be updated or recompiled") + +PYTHON_SUPPORT = hasattr(_psyco, 'turbo_code') + + +if hasattr(_psyco, 'ALL_CHECKS') and hasattr(_psyco, 'VERBOSE_LEVEL'): + print >> sys.stderr, ('psyco: running in debugging mode on %s' % + _psyco.PROCESSOR) + + +########################################################################### +# sys._getframe() gives strange results on a mixed Psyco- and Python-style +# stack frame. Psyco provides a replacement that partially emulates Python +# frames from Psyco frames. The new sys._getframe() may return objects of +# a custom "Psyco frame" type, which with Python >=2.2 is a subtype of the +# normal frame type. +# +# The same problems require some other built-in functions to be replaced +# as well. Note that the local variables are not available in any +# dictionary with Psyco. + + +class Frame: + pass + + +class PythonFrame(Frame): + + def __init__(self, frame): + self.__dict__.update({ + '_frame': frame, + }) + + def __getattr__(self, attr): + if attr == 'f_back': + try: + result = embedframe(_psyco.getframe(self._frame)) + except ValueError: + result = None + except error: + warn("f_back is skipping dead Psyco frames") + result = self._frame.f_back + self.__dict__['f_back'] = result + return result + else: + return getattr(self._frame, attr) + + def __setattr__(self, attr, value): + setattr(self._frame, attr, value) + + def __delattr__(self, attr): + delattr(self._frame, attr) + + +class PsycoFrame(Frame): + + def __init__(self, tag): + self.__dict__.update({ + '_tag' : tag, + 'f_code' : tag[0], + 'f_globals': tag[1], + }) + + def __getattr__(self, attr): + if attr == 'f_back': + try: + result = embedframe(_psyco.getframe(self._tag)) + except ValueError: + result = None + elif attr == 'f_lineno': + result = self.f_code.co_firstlineno # better than nothing + elif attr == 'f_builtins': + result = self.f_globals['__builtins__'] + elif attr == 'f_restricted': + result = self.f_builtins is not __builtins__ + elif attr == 'f_locals': + raise AttributeError, ("local variables of functions run by Psyco " + "cannot be accessed in any way, sorry") + else: + raise AttributeError, ("emulated Psyco frames have " + "no '%s' attribute" % attr) + self.__dict__[attr] = result + return result + + def __setattr__(self, attr, value): + raise AttributeError, "Psyco frame objects are read-only" + + def __delattr__(self, attr): + if attr == 'f_trace': + # for bdb which relies on CPython frames exhibiting a slightly + # buggy behavior: you can 'del f.f_trace' as often as you like + # even without having set it previously. + return + raise AttributeError, "Psyco frame objects are read-only" + + +def embedframe(result): + if type(result) is type(()): + return PsycoFrame(result) + else: + return PythonFrame(result) + +def _getframe(depth=0): + """Return a frame object from the call stack. This is a replacement for +sys._getframe() which is aware of Psyco frames. + +The returned objects are instances of either PythonFrame or PsycoFrame +instead of being real Python-level frame object, so that they can emulate +the common attributes of frame objects. + +The original sys._getframe() ignoring Psyco frames altogether is stored in +psyco._getrealframe(). See also psyco._getemulframe().""" + # 'depth+1' to account for this _getframe() Python function + return embedframe(_psyco.getframe(depth+1)) + +def _getemulframe(depth=0): + """As _getframe(), but the returned objects are real Python frame objects +emulating Psyco frames. Some of their attributes can be wrong or missing, +however.""" + # 'depth+1' to account for this _getemulframe() Python function + return _psyco.getframe(depth+1, 1) + +def patch(name, module=__builtin__): + f = getattr(_psyco, name) + org = getattr(module, name) + if org is not f: + setattr(module, name, f) + setattr(_psyco, 'original_' + name, org) + +_getrealframe = sys._getframe +sys._getframe = _getframe +patch('globals') +patch('eval') +patch('execfile') +patch('locals') +patch('vars') +patch('dir') +patch('input') +_psyco.original_raw_input = raw_input +__builtin__.__in_psyco__ = 0==1 # False + +if hasattr(_psyco, 'compact'): + import kdictproxy + _psyco.compactdictproxy = kdictproxy.compactdictproxy Added: trunk/lib/psyco/support.pyo =================================================================== (Binary files differ) Property changes on: trunk/lib/psyco/support.pyo ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Modified: trunk/lib/ror/starter.py =================================================================== --- trunk/lib/ror/starter.py 2007-06-23 11:34:40 UTC (rev 15) +++ trunk/lib/ror/starter.py 2007-06-23 14:41:59 UTC (rev 16) @@ -127,6 +127,6 @@ myFrame = SettingsDialog(None, -1, "") MainApp.SetTopWindow(myFrame) - myFrame.Show() - - MainApp.MainLoop() \ No newline at end of file + myFrame.Show() + + MainApp.MainLoop() Modified: trunk/lib/wxogre/wxOgreWindow.py =================================================================== --- trunk/lib/wxogre/wxOgreWindow.py 2007-06-23 11:34:40 UTC (rev 15) +++ trunk/lib/wxogre/wxOgreWindow.py 2007-06-23 14:41:59 UTC (rev 16) @@ -3,12 +3,14 @@ import ogre.renderer.OGRE as ogre from wxogre.OgreManager import * -class Struct: - "simple dummy class to regroup scene entities in a single parameter" - pass - class wxOgreWindow(wx.PyWindow): def __init__(self, parent, ID, size = wx.Size(200,200), **kwargs): + """ + @param parent: The parent wx Window + @param size: the minimal window size + @param kwargs: any other wx arguments + @return: none + """ wx.PyWindow.__init__(self, parent, ID, size = size, **kwargs) self.parent = parent @@ -29,25 +31,55 @@ self.SetFocus() def _OnSize(self, event): + """ + Is called when the ogre Window is getting resized + @param event: the sizing event + @return: none + """ if getattr(self, 'ogreRoot', None): self.renderWindow.windowMovedOrResized() event.Skip() def _OnEraseBackground(self, event): + """ + overwrite standart background drawing routing with empty one + @param event: the draw event + @return: none + """ # Do nothing, to avoid flashing on MSW. pass def _OnCloseWindow(self, event): + """ + called when the ogre window gets closed + @param event: the closing event + @return: none + """ self.Destroy() def AcceptsFocus(self): + """ + this window may accept keyboard focus + """ return True def SceneInitialisation(self): + """ + default, base function, that has to be overwritten in the inherited class. It gets called after create the window, and should select a scenemanger. + @return: none + """ pass def OnFrameStarted(self): + """ + default, base function, that has to be overwritten in the inherited class. gets called before rendering a frame. + @return: none + """ return def OnFrameEnded(self): + """ + default, base function, that has to be overwritten in the inherited class. gets called after rendering a frame. + @return: none + """ return Modified: trunk/ogre.cfg =================================================================== --- trunk/ogre.cfg 2007-06-23 11:34:40 UTC (rev 15) +++ trunk/ogre.cfg 2007-06-23 14:41:59 UTC (rev 16) @@ -1,4 +1,4 @@ -Render System=Direct3D9 Rendering Subsystem +Render System=OpenGL Rendering Subsystem [OpenGL Rendering Subsystem] Colour Depth=32 Modified: trunk/rortoolkit.py =================================================================== --- trunk/rortoolkit.py 2007-06-23 11:34:40 UTC (rev 15) +++ trunk/rortoolkit.py 2007-06-23 14:41:59 UTC (rev 16) @@ -1,7 +1,25 @@ #Thomas Fischer 31/05/2007, th...@th... import sys, os, os.path -if __name__=="__main__": +def main(): + """ + main method + """ + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) + + # Import Psyco if available + try: + import psyco + psyco.full() + #psyco.log() + #psyco.profile() + except ImportError: + pass + import ror.starter ror.starter.startApp() + + +if __name__=="__main__": + main() \ No newline at end of file Modified: trunk/terraineditor.py =================================================================== --- trunk/terraineditor.py 2007-06-23 11:34:40 UTC (rev 15) +++ trunk/terraineditor.py 2007-06-23 14:41:59 UTC (rev 16) @@ -1,17 +1,23 @@ #Thomas Fischer 31/05/2007, th...@th... import sys, os, os.path -if __name__=="__main__": +def main(): + """ + main method + """ + + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) + # Import Psyco if available try: import psyco psyco.full() - #psyco.log() - #psyco.profile() except ImportError: pass - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) import rorterraineditor.MainFrame rorterraineditor.MainFrame.startApp() + +if __name__=="__main__": + main() \ No newline at end of file Modified: trunk/truckeditor.py =================================================================== --- trunk/truckeditor.py 2007-06-23 11:34:40 UTC (rev 15) +++ trunk/truckeditor.py 2007-06-23 14:41:59 UTC (rev 16) @@ -1,7 +1,23 @@ #Thomas Fischer 31/05/2007, th...@th... import sys, os, os.path -if __name__=="__main__": +def main(): + """ + main method + """ + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) + + # Import Psyco if available + try: + import psyco + psyco.full() + except ImportError: + pass + import rortruckeditor.MainFrame rortruckeditor.MainFrame.startApp() + + +if __name__=="__main__": + main() \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-06-24 01:14:27
|
Revision: 17 http://roreditor.svn.sourceforge.net/roreditor/?rev=17&view=rev Author: rorthomas Date: 2007-06-23 18:14:22 -0700 (Sat, 23 Jun 2007) Log Message: ----------- * updated bugreport * added sysinfo tools * moved binaries to tools path Modified Paths: -------------- trunk/lib/ror/bugreport.py trunk/lib/ror/starter.py trunk/rortoolkit.py trunk/setup.nsi Added Paths: ----------- trunk/lib/sysinfo/ trunk/lib/sysinfo/README trunk/lib/sysinfo/__init__.py trunk/lib/sysinfo/common.py trunk/lib/sysinfo/linux/ trunk/lib/sysinfo/linux/__init__.py trunk/lib/sysinfo/linux/apt.py trunk/lib/sysinfo/linux/hardware.py trunk/lib/sysinfo/linux/misc.py trunk/lib/sysinfo/linux/my_rpm.py trunk/lib/sysinfo/linux/network.py trunk/lib/sysinfo/linux/services.py trunk/lib/sysinfo/sysinfo-example.py trunk/lib/sysinfo/win32/ trunk/lib/sysinfo/win32/__init__.py trunk/lib/sysinfo/win32/hardware.py trunk/lib/sysinfo/win32/misc.py trunk/lib/sysinfo/win32/services.py trunk/lib/sysinfo/win32/software.py trunk/tools/ trunk/tools/dxwebsetup.exe trunk/tools/pywin32-210.win32-py2.5.exe Removed Paths: ------------- trunk/dxwebsetup.exe Deleted: trunk/dxwebsetup.exe =================================================================== (Binary files differ) Modified: trunk/lib/ror/bugreport.py =================================================================== --- trunk/lib/ror/bugreport.py 2007-06-23 14:41:59 UTC (rev 16) +++ trunk/lib/ror/bugreport.py 2007-06-24 01:14:22 UTC (rev 17) @@ -1,5 +1,7 @@ import wx, os, os.path +BUGREPORT_FILENAME = "hwinfo.txt" + class BugReportFrame(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION | wx.CLIP_CHILDREN @@ -10,23 +12,79 @@ self.Bind(wx.EVT_BUTTON, self.onSubmit, self.btnSubmit) self.Bind(wx.EVT_BUTTON, self.onExit, self.btnCancel) self.__do_layout() - self.filename = "readme.txt" - self.LoadHelp() + self.generateSysinfo() + self.LoadHWFile() - def generateSsysinfo(self): + def generateSysinfo(self): import platform txt = "" - txt += ", ".join(platform.uname()) + "\n" - txt += ", ".join(platform.architecture()) + "\n" - txt += ", ".join(platform.platform()) + "\n" - txt += ", ".join(platform.version()) + "\n" - txt += ", ".join(platform.python_build()) + "\n" - txt += ", ".join(platform.python_version()) + "\n" + txt += "Platform: " + ", ".join(platform.uname()) + "\n" + txt += "Architecture: " + ", ".join(platform.architecture()) + "\n" + txt += "Platform: " + platform.platform() + "\n" + txt += "Version: " + platform.version() + "\n" + txt += "Python build: " + ", ".join(platform.python_build()) + "\n" + txt += "Python version:" + ", ".join(platform.python_version()) + "\n" + txt += self.getHWInfos() + self.writeFile(BUGREPORT_FILENAME, txt) + + def writeFile(self, filename, content): + outfile = open(filename, 'w') + outfile.write(content) + outfile.close() + + def getHWInfos(self): + import sysinfo + txt = "" + try: + hw = sysinfo.hardware() + except: + pass + try: + txt += "Motherboard: %s\n" % hw.motherboard.product + except: + pass + try: + txt += "Motherboard Vendor: %s\n" % hw.motherboard.vendor + except: + pass + try: + txt += "CPU: %s\n" % hw.cpu.product + except: + pass + try: + txt += "Motherboard Vendor: %s\n" % hw.cpu.vendor + except: + pass + try: + txt += "CPU Speed: %s\n" % hw.cpu.frequency + except: + pass + try: + txt += "Video memory: %.2fMB\n" % (float(hw.video_board.memory) / 1024 / 1024) + except: + pass + try: + txt += "HW Memory: %.2f MB\n" % (float(hw.memory.size) / 1024) + except: + pass + try: + txt += "GFX card: %s\n" % hw.video_board.product + except: + pass + try: + txt += "Resolution: %s@%d\n" % (hw.video_board.resolution, int(hw.video_board.width)) + except: + pass + try: + txt += "Sound card: %s\n" % hw.sound_board.product + except: + pass + return txt - def LoadHelp(self): - if os.path.isfile(self.filename): - self.TextCtrl.LoadFile(self.filename) + def LoadHWFile(self): + if os.path.isfile(BUGREPORT_FILENAME): + self.TextCtrl.LoadFile(BUGREPORT_FILENAME) def onSubmit(self, event=None): self.Close() @@ -39,7 +97,7 @@ sizer_2 = wx.BoxSizer(wx.HORIZONTAL) sizer_2.Add(self.TextCtrl, -1, wx.EXPAND, 0) sizer_main.Add(sizer_2, -1, wx.EXPAND, 0) - sizer_main.Add(self.btnExit, 0, wx.EXPAND, 0) + sizer_main.Add(self.btnSubmit, 0, wx.EXPAND, 0) self.SetAutoLayout(True) self.SetSizer(sizer_main) Modified: trunk/lib/ror/starter.py =================================================================== --- trunk/lib/ror/starter.py 2007-06-23 14:41:59 UTC (rev 16) +++ trunk/lib/ror/starter.py 2007-06-24 01:14:22 UTC (rev 17) @@ -27,6 +27,9 @@ self.btnStartTruckEditor = wx.Button(self.panel, wx.ID_ANY, "Start Truck Editor") self.Bind(wx.EVT_BUTTON, self.OnTruckEditor, self.btnStartTruckEditor) + self.btnBugReport = wx.Button(self.panel, wx.ID_ANY, "Report a Bug") + self.Bind(wx.EVT_BUTTON, self.OnBugReport, self.btnBugReport) + self.btnExit = wx.Button(self.panel, wx.ID_ANY, "Exit") self.Bind(wx.EVT_BUTTON, self.OnExit, self.btnExit) @@ -66,6 +69,13 @@ except: pass + def OnBugReport(self, event=None): + import ror.bugreport + #try: + ror.bugreport.showBugReportFrame() + #except: + # pass + def OnTerrainEditor(self, event=None): import rorterraineditor.MainFrame try: @@ -109,6 +119,7 @@ sizer_panel.Add(self.btnStartRoR, 0, wx.EXPAND, 0) sizer_panel.Add(self.btnStartTerrainEditor, 0, wx.EXPAND, 0) sizer_panel.Add(self.btnStartTruckEditor, 0, wx.EXPAND, 0) + sizer_panel.Add(self.btnBugReport, 0, wx.EXPAND, 0) sizer_panel.Add(self.btnExit, 0, wx.EXPAND, 0) self.panel.SetSizer(sizer_panel) Added: trunk/lib/sysinfo/README =================================================================== --- trunk/lib/sysinfo/README (rev 0) +++ trunk/lib/sysinfo/README 2007-06-24 01:14:22 UTC (rev 17) @@ -0,0 +1,21 @@ +== Python-sysinfo == +==================== + +Python-sysinfo provides an abstraction layer to system information for +hardware, software and services in the local computer. + +The GNU/Linux version uses lshw to collect hardware info and the other +data come from config files, /proc and such. + +Python-sysinfo is a component of NWU. + +See http://cetico.org/nwu + +For sample code of python-sysinfo in action, see doc/sysinfo-sample.py + + +Authors: +Yves Junqueira (nictuku) <yv...@ce...> +José Júnior (coredump) <jos...@gm...> + + Added: trunk/lib/sysinfo/__init__.py =================================================================== --- trunk/lib/sysinfo/__init__.py (rev 0) +++ trunk/lib/sysinfo/__init__.py 2007-06-24 01:14:22 UTC (rev 17) @@ -0,0 +1,80 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2006 José de Paula Eufrásio Junior (jos...@gm...) AND +# Yves Junqueira (yve...@gm...) +# +# 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; either version 2 of the License, or +# (at your option) any later version. +# +# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +"""Provides methods for collecting system information in +a portable way, for both Linux and Windows. +""" + +# The current structure will be replaced by the following: +# +# sysinfo.network().dnsdomains = list +# sysinfo.network().default_gateway = str +# sysinfo.network().interfaces = list +# sysinfo.network().interface() = method +# sysinfo.network().interface('eth0').ip_addresses = list +# sysinfo.network().interface('eth0').mac_address = str +# sysinfo.network().interface('eth0').product = str +# sysinfo.network().interface('eth0').vendor = str +# sysinfo.services.smb.workgroup = str +# sysinfo.services.smb.winsservers = list +# sysinfo.hardware.motherboard.product +# sysinfo.hardware.motherboard.vendor +# sysinfo.hardware.videoboard.product +# sysinfo.hardware.videoboard.vendor +# sysinfo.software.installed = list +# +# All data must be populated, even with empty values. +# +# Planned modules strucuture: +# +# sysinfo/ +# __init__.py +# linux/ +# __init__.py +# network.py network class +# services.py services class +# hardware.py provides hardware class +# +# + +import sys +import logging +import os + +logger = logging.getLogger("sysinfo") + +if sys.platform == 'linux2': + logger.info("Loading sysinfo for Linux") + from linux.network import network + from linux.hardware import hardware + from linux import services + from linux import misc + if os.path.isfile('/etc/debian_version'): + from linux import apt as software + elif os.path.isfile('/etc/redhat-release'): + from linux import my_rpm as software + +elif sys.platform == 'win32': + logger.info("Loading sysinfo for win32") + #from win32.network import network + from win32.hardware import hardware + from win32 import services + from win32 import software + from win32 import misc Added: trunk/lib/sysinfo/common.py =================================================================== --- trunk/lib/sysinfo/common.py (rev 0) +++ trunk/lib/sysinfo/common.py 2007-06-24 01:14:22 UTC (rev 17) @@ -0,0 +1,101 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2006 José de Paula Eufrásio Junior (jos...@gm...) AND +# Yves Junqueira (yve...@gm...) +# +# 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; either version 2 of the License, or +# (at your option) any later version. +# +# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +# from http://www.voidspace.org.uk/python/pathutils.html (BSD License) + +def formatbytes(sizeint, configdict=None, **configs): + """ + Given a file size as an integer, return a nicely formatted string that + represents the size. Has various options to control it's output. + + You can pass in a dictionary of arguments or keyword arguments. Keyword + arguments override the dictionary and there are sensible defaults for options + you don't set. + + Options and defaults are as follows : + + * ``forcekb = False`` - If set this forces the output to be in terms + of kilobytes and bytes only. + + * ``largestonly = True`` - If set, instead of outputting + ``1 Mbytes, 307 Kbytes, 478 bytes`` it outputs using only the largest + denominator - e.g. ``1.3 Mbytes`` or ``17.2 Kbytes`` + + * ``kiloname = 'Kbytes'`` - The string to use for kilobytes + + * ``meganame = 'Mbytes'`` - The string to use for Megabytes + + * ``bytename = 'bytes'`` - The string to use for bytes + + * ``nospace = True`` - If set it outputs ``1Mbytes, 307Kbytes``, + notice there is no space. + + Example outputs : :: + + 19Mbytes, 75Kbytes, 255bytes + 2Kbytes, 0bytes + 23.8Mbytes + + .. note:: + + It currently uses the plural form even for singular. + """ + defaultconfigs = { 'forcekb' : False, + 'largestonly' : True, + 'kiloname' : 'Kbytes', + 'meganame' : 'Mbytes', + 'bytename' : 'bytes', + 'nospace' : True} + if configdict is None: + configdict = {} + for entry in configs: + # keyword parameters override the dictionary passed in + configdict[entry] = configs[entry] + # + for keyword in defaultconfigs: + if not configdict.has_key(keyword): + configdict[keyword] = defaultconfigs[keyword] + # + if configdict['nospace']: + space = '' + else: + space = ' ' + # + mb, kb, rb = bytedivider(sizeint) + if configdict['largestonly']: + if mb and not configdict['forcekb']: + return stringround(mb, kb)+ space + configdict['meganame'] + elif kb or configdict['forcekb']: + if mb and configdict['forcekb']: + kb += 1024*mb + return stringround(kb, rb) + space+ configdict['kiloname'] + else: + return str(rb) + space + configdict['bytename'] + else: + outstr = '' + if mb and not configdict['forcekb']: + outstr = str(mb) + space + configdict['meganame'] +', ' + if kb or configdict['forcekb'] or mb: + if configdict['forcekb']: + kb += 1024*mb + outstr += str(kb) + space + configdict['kiloname'] +', ' + return outstr + str(rb) + space + configdict['bytename'] + + Added: trunk/lib/sysinfo/linux/__init__.py =================================================================== --- trunk/lib/sysinfo/linux/__init__.py (rev 0) +++ trunk/lib/sysinfo/linux/__init__.py 2007-06-24 01:14:22 UTC (rev 17) @@ -0,0 +1,25 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2006 José de Paula Eufrásio Junior (jos...@gm...) AND +# Yves Junqueira (yve...@gm...) +# +# 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; either version 2 of the License, or +# (at your option) any later version. +# +# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import logging +import sys + +logger = logging.getLogger("sysinfo.hardware.linux.init") + Added: trunk/lib/sysinfo/linux/apt.py =================================================================== --- trunk/lib/sysinfo/linux/apt.py (rev 0) +++ trunk/lib/sysinfo/linux/apt.py 2007-06-24 01:14:22 UTC (rev 17) @@ -0,0 +1,122 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2006 José de Paula Eufrásio Junior (jos...@gm...) +# AND# Yves Junqueira (yve...@gm...) +# +# 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; either version 2 of the License, or +# (at your option) any later version. +# +# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +"""Provides package management system information using APT +""" + +# thanks to http://users.sarai.net/shehjar/download/py-apt-tut.txt + +import apt_pkg +import os +import sys +import commands +import re +import logging + +logger = logging.getLogger("sysinfo.linux.apt") + +class packages: + + installed = [] + installed_ver = {} + update_candidates = {} + + def __init__(self): + # FIXME: These works, but isn't it ugly? + #os.close(1) + #os.close(2) + c = cache() + self.installed = c.installed_packages.keys() + self.installed.sort() + self.update_candidates = c.update_candidates + + for software in self.installed: + self.installed_ver[software] = c.installed_packages[software].VerStr + + +class cache: + + installed_packages = {} + update_candidates = {} + cache = '' + + def __init__(self): + + apt_pkg.init() + self.cache = apt_pkg.GetCache() + self.installed_packages = self._get_installed_packages() + self.update_candidates = self._get_update_candidates() + + + def _get_update_candidates(self): + + update_pkgs = {} + + try: + depcache = apt_pkg.GetDepCache(self.cache) + + except AttributeError: + # We are using an old version of libapt (like sarge's) + aptget = commands.getstatusoutput("export LANGUAGE=C; /usr/bin/env aptitude search '~U' -F '%p## %V##' 2> /dev/null") + if aptget[0] != 0: + logger.error("Error while trying to run apt-get upgrade") + logger.error("ERROR:" + str(aptget[1])) + return False + + get = aptget[1].split('\n') + for line in get: + h = re.compile('^(?P<pk_name>[\S]+)\s+(?P<pk_ver>[\S]+)') + p = h.search(line) + try: + if not (p.group('pk_name') and p.group('pk_ver')): + continue + except AttributeError: + continue + else: + update_pkgs[p.group('pk_name')] = p.group('pk_ver') + + else: + # Ok, new version of apt. This is the pretty way to do it :-) + depcache.ReadPinFile() + depcache.Init() + depcache.Upgrade() + + for pkg in self.cache.Packages: + if depcache.MarkedInstall(pkg) or depcache.MarkedUpgrade(pkg): + if depcache.GetCandidateVer(pkg) != pkg.CurrentVer: + update_pkgs[pkg.Name] = \ + depcache.GetCandidateVer(pkg).VerStr + return update_pkgs + + + def _get_installed_packages(self): + inst_pkgs = {} + + for pkg in self.cache.Packages: + if pkg.CurrentVer: + inst_pkgs[pkg.Name] = pkg.CurrentVer + return inst_pkgs + +if __name__ == '__main__': + s = packages() + #print "instalados", s.installed + #print "instalados_versao", s.installed_ver + print "update", s.update_candidates + Added: trunk/lib/sysinfo/linux/hardware.py =================================================================== --- trunk/lib/sysinfo/linux/hardware.py (rev 0) +++ trunk/lib/sysinfo/linux/hardware.py 2007-06-24 01:14:22 UTC (rev 17) @@ -0,0 +1,392 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2006 José de Paula Eufrásio Junior (jos...@gm...) AND +# Yves Junqueira (yve...@gm...) +# +# 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; either version 2 of the License, or +# (at your option) any later version. +# +# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +from xml.sax import ContentHandler +from xml.sax import make_parser +from xml.sax import parseString + +import StringIO +import xml.sax + +import commands +import logging +import string +import sys +import os + +logger = logging.getLogger("sysinfo.linux.hardware") + +# FIXME: teste feito em MDS500 mostrou que lshw às vezes gera um XML com +# caracteres estranhos, como ^E^D^D^C + +class lshw_run_error(Exception): + pass + +class lshw_data_parser(ContentHandler): + """Parse a XML file that was created using 'lshw -xml'. You need another + function to parse it and copy the contents of "HardWare". The class + "HardWare" below does that. + """ + + def __init__(self): + logger.debug("Created new instance for the 'lshw_data_parser' class") + # List of dicts containing Nodes data + self.Nodes = [] + # Dict containing current tag data. + self.CurrentTag = [{}] + + # String with the current tag represented unit, if available. + self.CurrentTagUnits = '' + # Dict containing relevant machine data. + # Every item should support multiple values + self.HardWare = {} + + def startElement(self, tag, attrs): + + self.CurrentTag.append({'name' : tag }) + # If it has a representation unit, set it. + # FIXME: this is returning the WRONG unit + # Disabled it temporarily until needed + #try: + # unit = attrs.get('units') + #except: + # self.CurrentTagUnits = '' + #else: + # if unit: + # self.CurrentTagUnits = unit + + if tag == 'node': + + self.Nodes.append({'name' : 'node' }) + + # Fill node attributes information + try: + nodeclass = attrs.get('class','') + except: + pass + else: + self.Nodes[-1]['class'] = nodeclass + + try: + nodehandle = attrs.get('handle','') + except: + pass + else: + self.Nodes[-1]['handle'] = nodehandle + + + def endElement(self, tag): + + # sanity test + if self.CurrentTag[-1]['name'] != tag: + sys.exit(1) + + else: + self.CurrentTag.pop() + if tag == 'node': + # Node closing. We should get all that and store somewhere, then + # pop it + # from the self.Nodes list. + node = self.Nodes[-1] + + if node.has_key('physid') and node.has_key('description'): + + self.setHardWare(node) + + else: + #print "Strange. Node lacks physid and/or description" + pass + + if len(self.Nodes) > 1: + # print "closing", tag + self.Nodes.pop() + + def characters(self, ch): + + # This will populate self.Nodes[-1] with relevant data. + # Not that it would only work for unique data (like physid) + for x in ['description', 'physid', 'product', 'vendor', 'version', + 'size', 'slot', 'width', 'serial']: + + if self.CurrentTag[-1]['name'] == x: + + if self.Nodes[-1].has_key(x): + self.Nodes[-1][x] += ch + else: + self.Nodes[-1][x] = ch + + def setHardWare(self, node): + """Argh. This is ugly. + """ + # FIXME: hmm what's the string for CD reader? + for element in ['CPU', 'BIOS', 'System Memory', 'System memory', + 'Motherboard', 'VGA compatible controller', + 'Multimedia audio controller', 'DVD-RAM writer', 'DVD reader', + 'Modem' ,'Mouse', 'Ethernet interface']: + + if node['description'] == element: + if not self.HardWare.has_key(element): + self.HardWare[element] = [] + + self.HardWare[element].append({}) + + for info in ['product', 'vendor', 'size','version', 'slot', + 'width', 'serial']: + if node.has_key(info): + set = node[info] + if info == 'size' and len(self.CurrentTagUnits) > 1: + unit = self.CurrentTagUnits + set += ' ' + unit + + self.HardWare[element][-1][info] = set + # In some cases (why?) 'System Memory' appears with + # a minor 'm'. + if element == 'System memory': + self.HardWare['System Memory'] = self.HardWare[element] + + +class get_hardware: + + def __init__(self): + parser = make_parser() + handler = lshw_data_parser() + parser.setContentHandler(handler) + logger.info("Calling lshw.") + + id = str(os.getuid()) + + if id != '0': + logger.error("In the current version, sysinfo hardware collection \ +requires root. Current uid: " + id) + print "Sysinfo must be run as root." + sys.exit(1) + + lshwxml = commands.getstatusoutput( + "export LANGUAGE=C; /usr/bin/env lshw -xml 2>&1|grep -v WARNING") + logger.info("lshw execution finished.") + + if lshwxml[0] != 0 or len(lshwxml[1]) < 1: + # This would kill this module instance. + # Should we handle it instead? + # 16/03/06: Die!! + logger.error("Could not run lshw") + raise lshw_run_error, "could not run lshw" + else: + xmldata = lshwxml[1] + + sane_data = '' + for char in xmldata: + if char in string.printable: + sane_data += char + + input = StringIO.StringIO(sane_data) + parser.parse(input) + self.data = handler.HardWare + +class keyboard: + """Get keyboard info from /proc/bus/input/devices + """ + + def __init__(self): + logger.debug("Getting keyboard data") + + try: + devices_file = open('/proc/bus/input/devices', 'r') + except: + pass + else: + + input = devices_file.readlines() + + for line in input: + if 'keyboard' in line: + k1 = line.replace('N: Name=','') + k2 = k1.replace('"','') + self.model = k2 + + +class motherboard: + + product = '' + vendor = '' + + def __init__(self, hw, index=0): + if hw.data.has_key('Motherboard'): + self.product = hw.data['Motherboard'][index].get('product', '') + self.vendor = hw.data['Motherboard'][index].get('vendor', '') + + +class memory: + + size = '' + + def __init__(self, hw): + if hw.data.has_key('System Memory'): + self.size = hw.data['System Memory'][0].get('size', '').replace(' bytes','') + +class mouse: + + product = '' + vendor = '' + + def __init__(self, hw, index=0): + if hw.data.has_key('Mouse'): + self.product = hw.data['Mouse'][index].get('product', '') + self.vendor = hw.data['Mouse'][index].get('vendor', '') + + +class modem: + + product = '' + vendor = '' + + def __init__(self, hw, index=0): + if hw.data.has_key('Modem'): + self.product = hw.data['Modem'][index].get('product', '') + self.vendor = hw.data['Modem'][index].get('vendor', '') + +class dvd_reader: + + product = '' + + def __init__(self, hw, index=0): + if hw.data.has_key('DVD reader'): + self.product = hw.data['DVD reader'][index].get('product', '') + +class dvd_ram_writer: + + product = '' + serial = '' + vendor = '' + + + def __init__(self, hw, index=0): + if hw.data.has_key('DVD-RAM writer'): + self.product = hw.data['DVD-RAM writer'][index].get('product', '') + self.serial = hw.data['DVD-RAM writer'][index].get('serial', '') + self.version = hw.data['DVD-RAM writer'][index].get('version', '') + +class bios: + + product = '' + size = '' + vendor = '' + + def __init__(self, hw): + if hw.data.has_key('BIOS'): + self.product = hw.data['BIOS'][0].get('product', '') + self.vendor = hw.data['BIOS'][0].get('vendor', '') + self.version = hw.data['BIOS'][0].get('version', '') + + + +class video_board: + + product = '' + size = '' + width = '' + vendor = '' + + def __init__(self, hw, index=0): + if hw.data.has_key('VGA compatible controller'): + self.product = \ + hw.data['VGA compatible controller'][index].get('product') + self.memory = \ + hw.data['VGA compatible controller'][index].get('size').replace(' bytes','') + self.width = \ + hw.data['VGA compatible controller'][index].get('width') + self.vendor = \ + hw.data['VGA compatible controller'][index].get('vendor') + +class sound_board: + + product = '' + + def __init__(self, hw, index=0): + if hw.data.has_key('Multimedia audio controller'): + self.product = \ + hw.data['Multimedia audio controller'][index].get('product') + +class ethernet_board: + + product = '' + size = '' + vendor = '' + width = '' + vendor = '' + serial = '' + + def __init__(self, hw, index=0): + + if hw.data.has_key('Ethernet interface'): + self.product = \ + hw.data['Ethernet interface'][index].get('product', '') + self.width = \ + hw.data['Ethernet interface'][index].get('width', '') + self.vendor = \ + hw.data['Ethernet interface'][index].get('vendor', '') + self.version = \ + hw.data['Ethernet interface'][index].get('version', '') + self.serial = \ + hw.data['Ethernet interface'][index].get('serial', '') + +class cpu: + + product = '' + size = '' + vendor = '' + + def __init__(self, hw, index=0): + if hw.data.has_key('CPU'): + self.product = hw.data['CPU'][index].get('product', '') + self.vendor = hw.data['CPU'][index].get('vendor', '') + self.frequency = hw.data['CPU'][index].get('size', '') + +class hardware: + """This is the interfaced accessed by the user. It provides + hardware data collected through get_hardware. + """ + # FIXME: motherboard, cpu, etc need support to multiple values. Currently + # uses index=0 + + def __init__(self): + logger.debug("Created new instance for the 'hardware' class") + self.hw = get_hardware() + self.motherboard = motherboard(self.hw, 0) + self.cpu = cpu(self.hw, 0) + self.ethernet_board = ethernet_board(self.hw, 0) + self.video_board = video_board(self.hw, 0) + self.sound_board = sound_board(self.hw, 0) + self.bios = bios(self.hw) # BIOS is always index=0 + self.dvd_reader = dvd_reader(self.hw, 0) + self.dvd_ram_writer = dvd_ram_writer(self.hw, 0) + self.modem = modem(self.hw, 0) + self.mouse = mouse(self.hw, 0) + self.memory = memory(self.hw) + self.keyboard = keyboard() + +if __name__ == '__main__': +# a = get_hardware() +# print a.data + x = hardware() + y = x.motherboard + print "h", x.motherboard.vendor, x.ethernet_board.product, \ + x.video_board.product, x.video_board.vendor,\ + x.dvd_reader.product, x.memory.size Added: trunk/lib/sysinfo/linux/misc.py =================================================================== --- trunk/lib/sysinfo/linux/misc.py (rev 0) +++ trunk/lib/sysinfo/linux/misc.py 2007-06-24 01:14:22 UTC (rev 17) @@ -0,0 +1,95 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (C) 2006 José de Paula Eufrásio Junior (jos...@gm...) +# AND# Yves Junqueira (yve...@gm...) +# +# 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; either version 2 of the License, or +# (at your option) any later version. +# +# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +"""Provides miscelaneous information like enviroment variables and local +partitions. +""" + +import os +import logging + + +logger = logging.getLogger("sysinfo.linux.misc") + +class env: + variables = {} + + def __init__(self): + + self.variables = os.environ + +class disks: + partitions = {} + + def __init__(self): + + self.partitions = self._get_partitions() + + def _get_partitions(self, show_remote=0,show_dummy=0): + """Get mounted partitions + Get mounted partitions. If show_remote=0, show only local partitions. + """ + + # + #From coreutils mountlist.c: + # + # /* A file system is `remote' if its Fs_name contains a `:' + # or if (it is of type smbfs and its Fs_name starts with `//'). */ + # + # + parts = [] + mtab = open('/etc/mtab', 'r') + for part in mtab.readlines(): + [fsname, mountp, fstype, options, dump, ppass ] = part.split() + # mtab brings octal escaped special strings + mountp = mountp.decode('string_escape') + if show_remote == 0: + if fsname.find(':') >= 0 : continue + if fstype == 'smbfs' and \ + fsname.startswith('//'): continue + + if show_dummy == 0: + # another possibility is to check /proc/filesystems and exclude any + # that has 'nodev' + if fstype == 'tmpfs' or fstype == 'proc' \ + or fstype == 'sysfs' or fstype == 'devpts' \ + or fstype == 'none' \ + or not fsname.startswith('/'): continue + + partstat = os.statvfs(mountp) + part_dict = { + 'fsname' : fsname, + 'mountpoint' : mountp, + 'fstype' : fstype, + 'fssize' : partstat[1] * partstat[2], + # bytes available for non-root + 'fsfree' : partstat[1] * partstat[4], + } + + parts.append(part_dict) + + mtab.close() + return parts + +if __name__ == '__main__': + e = env() +# print e.variables + d = disks() + print d.partitions[0]['fssize'] /(1024 * 1024) + print d.partitions[0]['fsfree'] / (1024 * 1024) Added: trunk/lib/sysinfo/linux/my_rpm.py =================================================================== --- trunk/lib/sysinfo/linux/my_rpm.py (rev 0) +++ trunk/lib/sysinfo/linux/my_rpm.py 2007-06-24 01:14:22 UTC (rev 17) @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2006 José de Paula Eufrásio Junior (jos...@gm...) +# AND# Yves Junqueira (yve...@gm...) +# +# 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; either version 2 of the License, or +# (at your option) any later version. +# +# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +"""Provides package management system information using RPM +""" + +# thanks to http://users.sarai.net/shehjar/download/py-apt-tut.txt + +import rpm +import logging + +logger = logging.getLogger("sysinfo.linux.rpm") + +class packages: + + installed = [] + installed_ver = {} + update_candidates = {} + + def __init__(self): + self.installed = self._get_installed() + self.installed.sort() + + def _get_installed(self): + """Gets installed packages information using RPM. + """ + ins_pkgs = [] + ts = rpm.TransactionSet() + mi = ts.dbMatch() # all installed packages + for h in mi: + ins_pkgs.append(h['name']) + return ins_pkgs + +if __name__ == '__main__': + s = packages() + print "instalados", s.installed + #print "instalados_versao", s.installed_ver + print "update", s.update_candidates + Added: trunk/lib/sysinfo/linux/network.py =================================================================== --- trunk/lib/sysinfo/linux/network.py (rev 0) +++ trunk/lib/sysinfo/linux/network.py 2007-06-24 01:14:22 UTC (rev 17) @@ -0,0 +1,416 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2006 José de Paula Eufrásio Junior (jos...@gm...) AND +# Yves Junqueira (yve...@gm...) +# +# 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; either version 2 of the License, or +# (at your option) any later version. +# +# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +"""Provides network information for linux systems +""" + +import commands +import logging +import re +import socket +import struct +import sys + +logger = logging.getLogger("sysinfo.linux.network") + +# auxiliary functions +def hex2dec(s): + """Returns the integer value of a hexadecimal string s + """ + return int(s, 16) +# Functions based on: +# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66517 +# which is licensed under the BSD license. + +def dottedQuadToNum(ip): + """convert decimal dotted quad string to long integer""" + return struct.unpack('L',socket.inet_aton(ip))[0] + +def numToDottedQuad(n): + """Convert long int to dotted quad string + """ + return socket.inet_ntoa(struct.pack('L',n)) + +def convert_ip_to_net_and_host(ip, maskstring): + """Returns tuple (network, host) dotted-quad addresses given IP and mask""" + # (by Greg Jorgensen) + + n = dottedQuadToNum(ip) + m = dottedQuadToNum(maskstring) + + host = n & m + net = n - host + + return numToDottedQuad(net), numToDottedQuad(host) + + +class ifconfig: + """Gets information from /sbin/ifconfig + and populates interf_dict + """ + + interf_dict = {} + + def __init__(self): + logger.info("Reading ifconfig data") + # Sets 'ifconfig' + ifconfig = commands.getstatusoutput("export LANGUAGE=C; ifconfig") + if ifconfig[0] != 0: + # This would kill this module instance. + logger.error("Could not run ifconfig") + raise IfconfigError, "could not run ifconfig" + else: + i = ifconfig[1] + sp = re.compile('([ae]th[\d]+|lo) ') + interf_list = sp.split(i) + interf_list.pop(0) + i = 1 + # Assemble a dict using 1 as key, 2 as value; 3 as key, 4 as value... + for x in interf_list: + if i % 2 == 0: # Even + self.interf_dict[ interf_list[i - 2] ] = x + i += 1 + + + +class resolv: + """Gets resolver information from /etc/resolv.conf + and populates resolvconf, dns_domain and dns_resolvers + """ + + resolvconf = '' + dns_domain = '' + dns_resolvers = '' + + def __init__(self): + # Return empty resolvconf. Do not raise error. + + self.resolvconf = self._get_resolvconf() + self.dns_domain = self._get_dns_domain() + self.dns_resolvers = self._get_dnsresolvers() + + def _get_resolvconf(self): + logger.debug("Getting DNS resolvers data") + try: + r = open('/etc/resolv.conf','r') + except: + logger.error("Error while reading /etc/resolv.conf") + return '' + else: + return r.read() + r.close() + + def _get_dns_domain(self): + + h = re.compile( r'(domain|search)\s+(?P<domain>.*)\s*', + re.I) + w = h.search(self.resolvconf) + if w: + domain = w.group('domain') + if domain: + return domain + + return '' + + def _get_dnsresolvers(self): + + r = re.compile( r'([\W]nameserver)\s+(?P<resolver>\S+)\s*' + r'((nameserver)\s+(?P<resolver2>\S+)\s*)?', + re.I) + + x = r.search(self.resolvconf) + #Resolvers must return at least two empty values + resolvers = ['',''] + if x: + resolver = x.group('resolver') + if resolver: + resolvers[0]= resolver + + resolver2 = x.group('resolver2') + + if resolver2: + resolvers[1] = resolver2 + + if resolvers is not None: + return resolvers + else: + return [] + +class misc: + """Gets miscelaneous information from the system. + """ + + hostname = '' + default_gateway = '' + interfaces = [] + + def __init__(self, ifc): + self.hostname = socket.gethostname() + self.default_gateway = self._get_default_gateway() + self.interfaces = ifc.interf_dict.keys() + + def _get_default_gateway(self): + t1 = self._get_default_gateway_from_proc() + if not t1: + t1 = self._get_default_gateway_from_bin_route() + if not t1: + return None + return t1 + + def _get_default_gateway_from_proc(self): + """"Returns the current default gateway, reading that from /proc' + """ + logger.debug("Reading default gateway information from /proc") + try: + f = open('/proc/net/route','r') + route = f.read() + except: + logger.error("Failed to read def gateway from /proc") + return None + else: + h = re.compile('\n(?P<interface>\w+)\s+00000000\s+(?P<def_gateway>[\w]+)\s+') + w = h.search(route) + if w: + if w.group('def_gateway'): + return numToDottedQuad(hex2dec(w.group('def_gateway'))) + else: + logger.error("Could not find def gateway info in /proc") + return None + else: + logger.error("Could not find def gateway info in /proc") + return None + + + def _get_default_gateway_from_bin_route(self): + """Get Default Gateway from '/sbin/route -n + Called by get_default_gateway and is only used if could not get that from /proc + """ + logger.debug("Reading default gateway information from route binary") + routebin = commands.getstatusoutput("export LANGUAGE=C; /usr/bin/env route -n") + + if routebin[0] != 0: + logger.error("Error while trying to run route") + return false + h = re.compile('\n0.0.0.0\s+(?P<def_gateway>[\w.]+)\s+') + w = h.search(routebin[1]) + if w: + def_gateway = w.group('def_gateway') + + if def_gateway: + return def_gateway + + logger.error("Could not find default gateway by running route") + return '' + +class interface: + """Retrieves interface specific information + """ + + ip_addresses = [] + mac_address = '' + netmask = '' + ip_network = '' + + def __init__(self, ifc, interf=None): + self.interf_dict = ifc.interf_dict + + if interf: + self.ip_addresses = self._get_ip_addresses(interf) + self.mac_address = self._get_mac_address(interf) + self.netmask = self._get_netmask(interf) + self.ip_network = self._get_network(self.ip_addresses[0], + self.netmask) + self.status = self._get_status(interf) + self.dhcp_server = self._get_dhcp_server(interf) + + def _get_ip_addresses(self, interf=None): + """Shows the interface's respective IP addresses + """ + # FIXME: get_address currently returns a singleton list. + + h = re.compile(r'inet add?r:(?P<ip_addr>[\w.]+)', re.I) + try: + w = h.search(self.interf_dict[interf]) + except KeyError: + logger.error("Could not find " + str(interf) + " in the list of \ +active network interfaces. Please review your configuration.") + sys.exit(1) + + ip_addrs = [] + if w: + ip_addrs.append(w.group('ip_addr')) + return ip_addrs + + + def _get_mac_address(self,interf=None): + """Gives network interfaces hardware address + """ + mac = '' + if interf: + h = re.compile(r'HW(addr)? (?P<mac>[\w:]+) ', re.I) + w = h.search(self.interf_dict[interf]) + if w: + mac = w.group('mac') + return mac + + def _get_network(self,ip=None,netmask=None): + + network = '' + + if ip and netmask: + (host, network) = convert_ip_to_net_and_host(ip, netmask) + return network + + def _get_netmask(self,interf=None): + """Shows the interface's respective IP netmask + """ + netmask = '' + + if interf: + h = re.compile(r'Mask:(?P<netmask>[\w.]+)', re.I) + w = h.search(self.interf_dict[interf]) + if w: + netmask = w.group('netmask') + return netmask + + def _get_status(self,interf=None): + """Shows interface status + """ + + if interf: + h = re.compile('UP',re.I) + w = h.search(self.interf_dict[interf]) + if w: + return 'UP' + else: + return 'DOWN' + else: + return '' + + def _get_dhcp_server(self,interf=None): + """Return the current DHCP Server for the 'interf' interface, by parsing the dhclient.leases file. + It will try to define if the IP was indeed setup using DHCP by trying to find dhclient in the + current running process list. + In case there are many leases stored, it should consider the last one for the given interface. + """ + + if interf == None: + return '' + + # FIXME if there is a better way to define if a machine is using DHCP + # besides checking dhclient? + + dh = commands.getstatusoutput('ps aux|grep dhclient') + + if dh[0] != 0: + logger.error("Error finding a running dhclient") + return '' + else: + i = dh[1] + sp = re.compile('-lf\s+(?P<leases_file>\S+)\s+.*(?P<interface>[ae]th[\d]+|lo)') + m = sp.search(dh[1]) + if m: + leases_file = m.group('leases_file') + else: + #FIXME: this should work for other distros and dhclient versions + leases_file = '/var/lib/dhcp3/dhclient.leases' + try: + f = open(leases_file) + except: + logger.error("Could not open leases_file (tried from " + \ + leases_file + " )") + return '' + dhcp = f.read() + f.close() + + sp = re.compile('(lease)\s*{') + leases_list = sp.split(dhcp) + + test_int = re.compile('interface\s*"'+ interf) + + # Removing leases unrelated to 'interf' + for x in leases_list: + m = test_int.search(x) + if not m: + leases_list.remove(x) + if len(leases_list) == 0: + return '' + lease = leases_list.pop() + + o = re.compile('option\s+dhcp-server-identifier\s+(?P<dhcp_server>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*;') + k = o.search(lease) + + if k: + server = k.group('dhcp_server') + else: + server = '' + + # Shows the last lease + return server + +class last_logon: + + last_user = '' + + def __init__(self): + self.last_user = self._get_last_user() + + def _get_last_user(self): + logger.debug("Getting last logon") + l = commands.getstatusoutput('export LANGUAGE=C; last') + if l[0] != 0: + logger.error("Error while running 'last'") + return '' + else: + last_f = l[1].split()[0] + return last_f + +class network(resolv, ifconfig, misc, last_logon): + """This is the stuff users will access. It inherits data from other 'os' + classes so users can access information like network.dns_domain. + """ + + def __init__(self): + self._ifc = ifconfig() + resolv.__init__(self) + misc.__init__(self, self._ifc) + last_logon.__init__(self) + self.interface = self.interface_wrapper + + def interface_wrapper(self, interf): + i = interface(self._ifc, interf) + return i + +if __name__ == '__main__': +# Log para stdout + format = "%(asctime)s %(levelname)s %(message)s" + logger.setLevel(logging.DEBUG) + ch = logging.StreamHandler() + ch.setLevel(logging.DEBUG) + formatter = logging.Formatter(format) + ch.setFormatter(formatter) + logger.addHandler(ch) + + g = network() + + #print i.interf_dict + #print d.dns_domain, d.dns_resolvers + b = g.interface(g.interfaces[1]) + print "teste", g.interfaces, b.ip_addresses, g.last_user, b.dhcp_server Added: trunk/lib/sysinfo/linux/services.py =================================================================== --- trunk/lib/sysinfo/linux/services.py (rev 0) +++ trunk/lib/sysinfo/linux/services.py 2007-06-24 01:14:22 UTC (rev 17) @@ -0,0 +1,153 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2006 José de Paula Eufrásio Junior (jos...@gm...) AND +# Yves Junqueira (yve...@gm...) +# +# 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; either version 2 of the License, or +# (at your option) any later version. +# +# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +"""Provides specific services information +""" + +import re +import logging + +logger = logging.getLogger("sysinfo.linux.services") + +class smb: + """Provides information from the SMB service using information from + the smb.conf file. + That may not be an exact science, but it's the best method available. + """ + + def __init__(self): + + conf = self._get_smbconf() + self.workgroup = self._get_workgroup(conf) + self.wins_servers = self._get_wins_servers(conf) + self.smb_shares = self._get_smb_shares(conf) + + def _get_smbconf(self): + try: + # In Debian-like distros + f = open('/etc/samba/smb.conf','r') + except: + try: + f = open('/etc/smb/smb.conf','r') + except: + logger.error("Error while opening smb.conf") + return '' + + smbconf = f.read() + f.close() + if not smbconf: + logger.error("Empty smb.conf") + return '' + else: + return smbconf + + + + def _get_workgroup(self, smbconf): + """Gets the workgroup from which the machine is a member + """ + + m = re.compile(r'^\s*workgroup\s*=\s*(?P<workgroup>.*)',re.I|re.M) + + p = m.search(smbconf) + + workgroup = '' + try: + workgroup = p.group('workgroup') + except: + pass + + return workgroup + + + def _get_smb_shares(self, smbconf): + """Gets the SMB shares in the config file + """ + conf = smbconf.split('\n') + + exclude = [ 'global' ] + share_search = re.compile(r'^\s*\[(?P<share>[^\]]+)\][\s]*(#.*)?$') + comment_search = re.compile(r'^\s*comment\s*=\s*(?P<comment>.*)$') + # list of dicts: + shares = [] + cur_share = '' + for line in conf: + share_match = share_search.search(line) + try: + share = share_match.group('share') + except: + pass + else: + if share not in exclude: + shares.append({'name': share}) + if share in ['printers', 'print$']: + # printer share + shares[-1]['type'] = 'printer' + else: + shares[-1]['type'] = 'directory' + cur_share = share + continue + else: + # beggining a new conf section + cur_share = '' + continue + + # we are only interested if we have a valid share + if cur_share: + comment_match = comment_search.search(line) + try: + comment = comment_match.group('comment') + except: + pass + else: + shares[-1]['comment'] = comment + + return shares + + def _get_wins_servers(self, smbconf): + """Gets the WINS servers in use by the machine + """ + + m = re.compile(r'^\s*wins server\s*=\s*(?P<wins>.*)',re.I|re.M) + + p = m.search(smbconf) + wins = [] + + try: + wins_string = p.group('wins') + except: + logger.error("Could not find WINS server setting") + else: + if wins_string: + wins = wins_string.split(' ') + else: + logger.error("Could not find WINS server setting") + + return wins + +if __name__ == '__main__': + + s = smb() + + #print i.interf_dict + #print d.dnsdomain, d.dnsresolvers + print "teste", s.workgroup,s.wins_servers,s.smb_shares + + Added: trunk/lib/sysinfo/sysinfo-example.py =================================================================== --- trunk/lib/sysinfo/sysinfo-example.py (rev 0) +++ trunk/lib/sysinfo/sysinfo-example.py 2007-06-24 01:14:22 UTC (rev 17) @@ -0,0 +1,64 @@ +#!/usr/bin/python + +#Sample python-sysinfo usage + +import sysinfo +import logging + +format = "%(asctime)s %(levelname)s %(message)s" +sysinfo_log = logging.getLogger("sysinfo") +sysinfo_log.setLevel(logging.DEBUG) +ch = logging.StreamHandler() +ch.setLevel(logging.DEBUG) +formatter = logging.Formatter(format) +ch.setFormatter(formatter) +sysinfo_log.addHandler(ch) + + +net = sysinfo.network() +interf = net.interface('eth0') +last_user = net.last_user + +hw = sysinfo.hardware() + +smb = sysinfo.services.smb() + +pkgs = sysinfo.software.packages() + +env = sysinfo.misc.env() + +print hw.motherboard.product +print hw.motherboard.vendor +print hw.cpu.product +print hw.cpu.vendor +print hw.cpu.frequency +print hw.video_board.memory +print hw.memory.size +print hw.video_board.product +print hw.sound_board.product +print hw.keyboard.model +print hw.bios.vendor +print hw.bios.version +print hw.dvd_reader.product +print hw.modem.vendor +print hw.modem.product +print hw.mouse.product +print hw.mouse.vendor +print hw.ethernet_board.vendor +print hw.ethernet_board.product + + +print net.hostname +print net.default_gateway +print net.dnsresolvers +print net.dnsdomain + + +print interf.dhcp_server +print interf.mac_address +print interf.ip_network +print interf.ip_addresses[0] + +print smb.smb_shares +print smb.wins_servers +print smb.workgroup Added: trunk/lib/sysinfo/win32/__init__.py =================================================================== Added: trunk/lib/sysinfo/win32/hardware.py =================================================================== --- trunk/lib/sysinfo/win32/hardware.py (rev 0) +++ trunk/lib/sysinfo/win32/hardware.py 2007-06-24 01:14:22 UTC (rev 17) @@ -0,0 +1,243 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright (C) 2006 José de Paula Eufrásio Junior (jos...@gm...) AND +# Yves Junqueira (yve...@gm...) +# +# 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; either version 2 of the License, or +# (at your option) any later version. +# +# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import win32com.client +import logging + +class get_hardware: + """Uses win32com to get hardware information. Script sampled from Microsoft. + """ + + data = {} + + def __init__(self): + target_list = [ + 'Win32_ComputerSystem', + 'Win32_BIOS', + #'Win32_Net... [truncated message content] |
From: <ror...@us...> - 2007-06-24 09:43:55
|
Revision: 18 http://roreditor.svn.sourceforge.net/roreditor/?rev=18&view=rev Author: rorthomas Date: 2007-06-24 02:43:41 -0700 (Sun, 24 Jun 2007) Log Message: ----------- improved bugreport Modified Paths: -------------- trunk/lib/ror/bugreport.py trunk/rortoolkit.py Added Paths: ----------- trunk/tools/pywin32-setup.exe Removed Paths: ------------- trunk/tools/pywin32-210.win32-py2.5.exe Modified: trunk/lib/ror/bugreport.py =================================================================== --- trunk/lib/ror/bugreport.py 2007-06-24 01:14:22 UTC (rev 17) +++ trunk/lib/ror/bugreport.py 2007-06-24 09:43:41 UTC (rev 18) @@ -5,10 +5,20 @@ class BugReportFrame(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION | wx.CLIP_CHILDREN - wx.Frame.__init__(self, *args, **kwds) - self.TextCtrl = wx.TextCtrl(self, wx.ID_ANY, style=wx.TE_RICH2|wx.TE_AUTO_URL|wx.TE_MULTILINE|wx.TE_READONLY,size=wx.Size(500,400)) - self.btnSubmit = wx.Button(self, wx.ID_ANY, "Submit") - self.btnCancel = wx.Button(self, wx.ID_ANY, "Cancel") + wx.Frame.__init__(self, *args, **kwds) + + self.panel = wx.Panel(self, wx.ID_ANY) + desc = """Please describe the Bug below: +some tips: +* if you give us an email in the text, we can answer you, otherwise not. +* it is good to take screenshots of errors, glitches and so on. + you can insert imageshack.us or equivalent URLs below.""" + self.lblText1 = wx.StaticText(self.panel, wx.ID_ANY, desc) + self.TextCtrlOwn = wx.TextCtrl(self.panel, wx.ID_ANY, style=wx.TE_RICH2|wx.TE_AUTO_URL|wx.TE_MULTILINE|wx.TE_READONLY,size=wx.Size(400,200)) + self.lblText2 = wx.StaticText(self.panel, wx.ID_ANY, "The gathered system information, that will be send along the description:") + self.TextCtrl = wx.TextCtrl(self.panel, wx.ID_ANY, style=wx.TE_RICH2|wx.TE_AUTO_URL|wx.TE_MULTILINE|wx.TE_READONLY,size=wx.Size(400,200)) + self.btnSubmit = wx.Button(self.panel, wx.ID_ANY, "Submit") + self.btnCancel = wx.Button(self.panel, wx.ID_ANY, "Cancel") self.Bind(wx.EVT_BUTTON, self.onSubmit, self.btnSubmit) self.Bind(wx.EVT_BUTTON, self.onExit, self.btnCancel) self.__do_layout() @@ -18,13 +28,14 @@ def generateSysinfo(self): import platform txt = "" - txt += "Platform: " + ", ".join(platform.uname()) + "\n" + txt += "Platform: %s, %s\n" % (platform.platform(), platform.version()) txt += "Architecture: " + ", ".join(platform.architecture()) + "\n" - txt += "Platform: " + platform.platform() + "\n" - txt += "Version: " + platform.version() + "\n" + txt += "Python version:" + "".join(platform.python_version()) + "\n" txt += "Python build: " + ", ".join(platform.python_build()) + "\n" - txt += "Python version:" + ", ".join(platform.python_version()) + "\n" - txt += self.getHWInfos() + hwinfo = self.getHWInfos() + if hwinfo == "": + return + txt += hwinfo self.writeFile(BUGREPORT_FILENAME, txt) def writeFile(self, filename, content): @@ -32,10 +43,32 @@ outfile.write(content) outfile.close() + # not working + # def installPyWin(self): + # dlg = wx.MessageDialog(self, "Python Windows extensions are required for this to work. I will try install them now in the Registry.\n", "Error", wx.OK | wx.ICON_INFORMATION) + # dlg.ShowModal() + # dlg.Destroy() + # import pywin32_postinstall + # pywin32_postinstall.install() + + def getHWInfos(self): - import sysinfo + + try: + import sysinfo + except: + dlg = wx.MessageDialog(self, "You must install pywin32 first.\nYou can find the setup in INSTALLDIR/tools/pywin32-setup.exe\nPLease note that you must restart this program after the pywin installation.", "Error", wx.OK | wx.ICON_INFORMATION) + dlg.ShowModal() + dlg.Destroy() + self.Close() + return "" + txt = "" try: + dlg = wx.MessageDialog(self, "This program will now try to figure out some Hardware Information. That can take a minute or so.", "Notice", wx.OK | wx.ICON_INFORMATION) + dlg.ShowModal() + dlg.Destroy() + hw = sysinfo.hardware() except: pass @@ -61,7 +94,7 @@ except: pass try: - txt += "Video memory: %.2fMB\n" % (float(hw.video_board.memory) / 1024 / 1024) + txt += "Video memory: %.2f MB\n" % (float(hw.video_board.memory) / 1024 / 1024) except: pass try: @@ -93,12 +126,18 @@ self.Close() def __do_layout(self): - sizer_main = wx.BoxSizer(wx.VERTICAL) - sizer_2 = wx.BoxSizer(wx.HORIZONTAL) - sizer_2.Add(self.TextCtrl, -1, wx.EXPAND, 0) - sizer_main.Add(sizer_2, -1, wx.EXPAND, 0) - sizer_main.Add(self.btnSubmit, 0, wx.EXPAND, 0) + sizer_panel = wx.BoxSizer(wx.VERTICAL) + sizer_panel.Add(self.lblText1, 0, wx.EXPAND, 0) + sizer_panel.Add(self.TextCtrlOwn, 0, wx.EXPAND, 0) + sizer_panel.Add(self.lblText2, 0, wx.EXPAND, 0) + sizer_panel.Add(self.TextCtrl, 0, wx.EXPAND, 0) + sizer_panel.Add(self.btnSubmit, 0, wx.EXPAND, 0) + sizer_panel.Add(self.btnCancel, 0, wx.EXPAND, 0) + self.panel.SetSizer(sizer_panel) + sizer_main = wx.BoxSizer(wx.VERTICAL) + sizer_main.Add(self.panel, 0, wx.EXPAND, 0) + self.SetAutoLayout(True) self.SetSizer(sizer_main) sizer_main.Fit(self) Modified: trunk/rortoolkit.py =================================================================== --- trunk/rortoolkit.py 2007-06-24 01:14:22 UTC (rev 17) +++ trunk/rortoolkit.py 2007-06-24 09:43:41 UTC (rev 18) @@ -7,7 +7,7 @@ """ sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib_win")) + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib\pywin32")) # Import Psyco if available try: Deleted: trunk/tools/pywin32-210.win32-py2.5.exe =================================================================== (Binary files differ) Copied: trunk/tools/pywin32-setup.exe (from rev 17, trunk/tools/pywin32-210.win32-py2.5.exe) =================================================================== (Binary files differ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-06-25 20:17:26
|
Revision: 28 http://roreditor.svn.sourceforge.net/roreditor/?rev=28&view=rev Author: rorthomas Date: 2007-06-25 13:17:24 -0700 (Mon, 25 Jun 2007) Log Message: ----------- * added tuusita's systemdrive fix to .bat files * removed some senseless controls from terraineditor * terraineditor now imports objects rather than meshs * fixed truck rotation Modified Paths: -------------- trunk/lib/ror/rorsettings.py trunk/lib/rorterraineditor/MainFrame.py trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py trunk/rortoolkit.bat trunk/terraineditor.bat trunk/truckeditor.bat Modified: trunk/lib/ror/rorsettings.py =================================================================== --- trunk/lib/ror/rorsettings.py 2007-06-25 18:04:46 UTC (rev 27) +++ trunk/lib/ror/rorsettings.py 2007-06-25 20:17:24 UTC (rev 28) @@ -24,8 +24,9 @@ def LoadRoRDir(self): try: f = open(self.configfilename,'r') - self.rordir = f.read() + self.rordir = os.path.abspath(f.read()) f.close() + print "Loaded RoR Directory: %s" % self.rordir except: print "error while loading rordir: %s" % self.configfilename Modified: trunk/lib/rorterraineditor/MainFrame.py =================================================================== --- trunk/lib/rorterraineditor/MainFrame.py 2007-06-25 18:04:46 UTC (rev 27) +++ trunk/lib/rorterraineditor/MainFrame.py 2007-06-25 20:17:24 UTC (rev 28) @@ -78,8 +78,8 @@ self.statusbar.SetStatusText("-", 1) #create toolbar - self.toolbar = wx.ToolBar(self, wx.ID_ANY, style = wx.TB_HORZ_TEXT) - self.SetToolBar(self.toolbar ) + #self.toolbar = wx.ToolBar(self, wx.ID_ANY, style = wx.TB_HORZ_TEXT) + #self.SetToolBar(self.toolbar ) #bitmap = wx.Bitmap("media/gui/OpenFile.gif", wx.BITMAP_TYPE_GIF) #self.toolbar.DoAddTool(0, "Open Terrain", bitmap, bitmap, wx.ITEM_NORMAL, "Open Terrain", "Opens a new terrain for edit") @@ -94,21 +94,21 @@ self.waterlevelctrl.max = 300 self.Bind(wx.EVT_SCROLL, self.OnChangeWaterLevel, self.waterlevelctrl) - self.CurrEntName = wx.StaticText(self, wx.ID_ANY, "") - self.PosText = wx.StaticText(self, wx.ID_ANY, "Position: x,y,z") - self.terrPosX = wx.TextCtrl(self, wx.ID_ANY) - self.terrPosY = wx.TextCtrl(self, wx.ID_ANY) - self.terrPosZ = wx.TextCtrl(self, wx.ID_ANY) - self.RotText = wx.StaticText(self, wx.ID_ANY, "Rotation: x,y,z") - self.terrRotX = wx.TextCtrl(self, wx.ID_ANY) - self.terrRotY = wx.TextCtrl(self, wx.ID_ANY) - self.terrRotZ = wx.TextCtrl(self, wx.ID_ANY) - self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrPosX) - self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrPosY) - self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrPosZ) - self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrRotX) - self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrRotY) - self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrRotZ) + self.CurrEntName = wx.StaticText(self, wx.ID_ANY, "\n\n\n") + #self.PosText = wx.StaticText(self, wx.ID_ANY, "Position: x,y,z") + #self.terrPosX = wx.TextCtrl(self, wx.ID_ANY) + #self.terrPosY = wx.TextCtrl(self, wx.ID_ANY) + #self.terrPosZ = wx.TextCtrl(self, wx.ID_ANY) + #self.RotText = wx.StaticText(self, wx.ID_ANY, "Rotation: x,y,z") + #self.terrRotX = wx.TextCtrl(self, wx.ID_ANY) + #self.terrRotY = wx.TextCtrl(self, wx.ID_ANY) + #self.terrRotZ = wx.TextCtrl(self, wx.ID_ANY) + #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrPosX) + #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrPosY) + #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrPosZ) + #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrRotX) + #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrRotY) + #self.Bind(wx.EVT_TEXT, self.OnChangeObjPosRot, self.terrRotZ) self.btnResetRotation = wx.Button(self, wx.ID_ANY, "Reset Rotation") self.Bind(wx.EVT_BUTTON, self.OnBtnResetRotation, self.btnResetRotation) @@ -139,7 +139,7 @@ add_menu = wx.Menu() add_menu.Append(ID_ADDTRUCK, "&Truck/Load", "add a Truck or a Load to the terrain") self.Bind(wx.EVT_MENU, self.OnAddTruck, id=ID_ADDTRUCK) - add_menu.Append(ID_ADDMESH, "&Mesh", "add a static Mesh to the terrain") + add_menu.Append(ID_ADDMESH, "&Object", "add a static Object to the terrain") self.Bind(wx.EVT_MENU, self.OnAddMesh, id=ID_ADDMESH) menuBar.Append(add_menu, "&Add"); @@ -180,17 +180,25 @@ dialog = wx.FileDialog(self, "Add Truck", default, "", "Truck and Load Files (*.truck,*.load)|*.truck;*.load", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) res = dialog.ShowModal() if res == wx.ID_OK: - self.terrainOgreWin.addTruckToTerrain(dialog.GetPath()) + if not self.terrainOgreWin.addTruckToTerrain(dialog.GetPath()): + dlg = wx.MessageDialog(self, "You must select a position on the ground first!", "error", wx.OK | wx.ICON_INFORMATION) + dlg.ShowModal() + dlg.Destroy() def OnAddMesh(self, event=None): default = "" if self.rordir: default = os.path.join(self.rordir, OBJECTDIR) print default - dialog = wx.FileDialog(self, "Add Mesh", default, "", "Ogre Meshs (*.mesh)|*.mesh", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) + dialog = wx.FileDialog(self, "Add Object", default, "", "RoR Object Definitions (*.odef)|*.odef", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) res = dialog.ShowModal() if res == wx.ID_OK: - self.terrainOgreWin.addMeshToTerrain(dialog.GetPath()) + print dialog.GetPath() + if not self.terrainOgreWin.addMeshToTerrain(dialog.GetPath()): + dlg = wx.MessageDialog(self, "You must select a position on the ground first!", "error", wx.OK | wx.ICON_INFORMATION) + dlg.ShowModal() + dlg.Destroy() + def OnBtnResetRotation(self, event=None): self.terrainOgreWin.ObjectResetRotation() @@ -202,18 +210,18 @@ if self.terrainOgreWin.mSelected is None: return n = self.terrainOgreWin.mSelected.getParentNode() - self.CurrEntName.Label = n.getName() - pos = n.getPosition() - self.terrPosX.SetValue(str(round(pos.x,2))) - self.terrPosY.SetValue(str(round(pos.y,2))) - self.terrPosZ.SetValue(str(round(pos.z,2))) - rot = n.getOrientation() - self.terrRotX.SetValue(str(round(ogre.Radian(rot.getPitch(False)+90).valueDegrees(),2))) - self.terrRotY.SetValue(str(round(ogre.Radian(rot.getYaw(False)).valueDegrees(),2))) - self.terrRotZ.SetValue(str(round(ogre.Radian(rot.getRoll(False)).valueDegrees(),2))) + self.CurrEntName.Label = "selected Object:\n%s" % n.getName() + #pos = n.getPosition() + #self.terrPosX.SetValue(str(round(pos.x,2))) + #self.terrPosY.SetValue(str(round(pos.y,2))) + #self.terrPosZ.SetValue(str(round(pos.z,2))) + #rot = n.getOrientation() + #self.terrRotX.SetValue(str(round(ogre.Radian(rot.getPitch(False)+90).valueDegrees(),2))) + #self.terrRotY.SetValue(str(round(ogre.Radian(rot.getYaw(False)).valueDegrees(),2))) + #self.terrRotZ.SetValue(str(round(ogre.Radian(rot.getRoll(False)).valueDegrees(),2))) def OnChangeObjPosRot(self, event=None): - self.terrainOgreWin.TerrainName = self.terrainNamectrl.GetValue() + pass def OnChangeTerrainNameChange(self, event=None): self.terrainOgreWin.TerrainName = self.terrainNamectrl.GetValue() @@ -264,7 +272,7 @@ dialog = wx.FileDialog(self, "Open Terrain", default, "", "Terrain Files (*.terrn)|*.terrn", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) res = dialog.ShowModal() if res == wx.ID_OK: - #self.fileopenmenu.Enable(False) + self.fileopenmenu.Enable(False) self.filesavemenu.Enable(True) self.filesaveasmenu.Enable(True) filename = dialog.GetPath() @@ -309,7 +317,7 @@ def OnExit(self, event): self.Close(True) del self - #sys.exit(0) + sys.exit(0) def __set_properties(self): self.SetTitle("RoREditor version 0.0.4") @@ -356,19 +364,19 @@ sizer_settings.Add(self.terrainNamectrl, 0, wx.EXPAND, 0) sizer_settings.Add(self.CurrEntName, 0, wx.EXPAND, 0) - sizer_settings.Add(self.PosText, 0, wx.EXPAND, 0) - sizer_terrPos = wx.BoxSizer(wx.HORIZONTAL) - sizer_terrPos.Add(self.terrPosX, 0, wx.EXPAND, 0) - sizer_terrPos.Add(self.terrPosY, 0, wx.EXPAND, 0) - sizer_terrPos.Add(self.terrPosZ, 0, wx.EXPAND, 0) - sizer_settings.Add(sizer_terrPos, 0, wx.EXPAND, 0) + #sizer_settings.Add(self.PosText, 0, wx.EXPAND, 0) + #sizer_terrPos = wx.BoxSizer(wx.HORIZONTAL) + #sizer_terrPos.Add(self.terrPosX, 0, wx.EXPAND, 0) + #sizer_terrPos.Add(self.terrPosY, 0, wx.EXPAND, 0) + #sizer_terrPos.Add(self.terrPosZ, 0, wx.EXPAND, 0) + #sizer_settings.Add(sizer_terrPos, 0, wx.EXPAND, 0) - sizer_settings.Add(self.RotText, 0, wx.EXPAND, 0) - sizer_terrRot = wx.BoxSizer(wx.HORIZONTAL) - sizer_terrRot.Add(self.terrRotX, 0, wx.EXPAND, 0) - sizer_terrRot.Add(self.terrRotY, 0, wx.EXPAND, 0) - sizer_terrRot.Add(self.terrRotZ, 0, wx.EXPAND, 0) - sizer_settings.Add(sizer_terrRot, 0, wx.EXPAND, 0) + #sizer_settings.Add(self.RotText, 0, wx.EXPAND, 0) + #sizer_terrRot = wx.BoxSizer(wx.HORIZONTAL) + #sizer_terrRot.Add(self.terrRotX, 0, wx.EXPAND, 0) + #sizer_terrRot.Add(self.terrRotY, 0, wx.EXPAND, 0) + #sizer_terrRot.Add(self.terrRotZ, 0, wx.EXPAND, 0) + #sizer_settings.Add(sizer_terrRot, 0, wx.EXPAND, 0) sizer_settings.Add(self.btnResetRotation, 0, wx.EXPAND, 0) sizer_settings.Add(self.btnStickToGround, 0, wx.EXPAND, 0) Modified: trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py =================================================================== --- trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py 2007-06-25 18:04:46 UTC (rev 27) +++ trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py 2007-06-25 20:17:24 UTC (rev 28) @@ -7,6 +7,8 @@ from random import random +ADDEDBY = "//added by the terrrain editor:\n" + class RoRTerrainOgreWindow(wxOgreWindow): #myObjects = {} @@ -145,6 +147,7 @@ f=open(self.rordir+"\\data\\objects\\%s.odef" % (objname), 'r') content = f.readlines() f.close() + meshname = content[0].strip() scalearr = content[1].split(",") self.myODefs[objname] = [] if len(content) > 2: @@ -153,9 +156,9 @@ if line.lower().strip() == "end": break self.myODefs[objname].append(line.split(",")) - return (float(scalearr[0]), float(scalearr[1]), float(scalearr[2])) + return (meshname, float(scalearr[0]), float(scalearr[1]), float(scalearr[2])) else: - return (1, 1, 1) + return (meshname, 1, 1, 1) except Exception, err: print "error while processing odef file of %s" % objname print str(err) @@ -275,17 +278,19 @@ n.setPosition(x, y, z) continue firstobjname = objname[0] - n = self.sceneManager.getRootSceneNode().createChildSceneNode("object" + str(i)+ firstobjname) - entname = "objent" + str(i)+"_"+firstobjname - e = self.sceneManager.createEntity(entname, firstobjname+".mesh") - n.attachObject(e) try: - (sx, sy, sz) = self.loadOdef(firstobjname) + (meshname, sx, sy, sz) = self.loadOdef(firstobjname) except Exception, inst: print inst print "########## error loading odef of %s" % firstobjname sx = None + + n = self.sceneManager.getRootSceneNode().createChildSceneNode("object" + str(i)+ firstobjname) + entname = "objent" + str(i)+"_"+firstobjname + e = self.sceneManager.createEntity(entname, meshname) + n.attachObject(e) + #print "position: ", x,", ", y,", ", z #print "rotation: ", rx,", ", ry,", ", rz #print "scale: ", sx,", ", sy,", ", sz @@ -361,9 +366,15 @@ rot = truck.getOrientation() truck.setScale(scale) - rotx = ogre.Radian(rot.getPitch(False)).valueDegrees() - 180 - rotz = ogre.Radian(rot.getRoll(False)).valueDegrees() - 180 - roty = - ogre.Radian(rot.getYaw(False)).valueDegrees() -180 + rotx = ogre.Radian(rot.getPitch(False)).valueDegrees() + rotz = ogre.Radian(rot.getRoll(False)).valueDegrees() + roty = - ogre.Radian(rot.getYaw(False)).valueDegrees() + if rotx != 0: + rotx -= 180 + if roty != 0: + roty -= 180 + if rotz != 0: + rotz -= 180 truckstring = k.split(".")[-1] + "\t " + k ar = [self.formatFloat(pos.x), self.formatFloat(pos.y), @@ -721,25 +732,44 @@ def addMeshToTerrain(self, fn): if self.selectedCoords is None: - return + return False + self.randomcounter += 1 - n = self.sceneManager.getRootSceneNode().createChildSceneNode("objectnode" + str(fn) + str(self.randomcounter)) - entname = "objent" + str(i)+str(self.randomcounter)+"_"+objname - e = self.sceneManager.createEntity(entname, objname+".mesh") + meshname = os.path.basename(fn) + (firstobjname, fileExtension) = os.path.splitext(meshname) + + try: + (meshname, sx, sy, sz) = self.loadOdef(firstobjname) + except Exception, inst: + print inst + print "########## error loading odef of %s" % firstobjname + sx = None + self.randomcounter +=1 + n = self.sceneManager.getRootSceneNode().createChildSceneNode("object" + str(self.randomcounter)+ firstobjname) + entname = "objent" + str(self.randomcounter)+"_"+firstobjname + e = self.sceneManager.createEntity(entname, meshname) n.attachObject(e) + n.setPosition(self.selectedCoords) n.rotate(ogre.Vector3.UNIT_X, ogre.Degree(-90),relativeTo=ogre.Node.TransformSpace.TS_WORLD) + if not sx is None: + n.setScale(sx, sy, sz) self.meshes[entname] = n + self.comments[entname] = [ADDEDBY] + self.meshesorder.append(entname) + return True + def addTruckToTerrain(self, fn): if self.selectedCoords is None: - return - n = self.createTruckMesh(fn) + return False + n, entname = self.createTruckMesh(fn) n.setPosition(self.selectedCoords) + return True def createTruckMesh(self, fn): if not os.path.isfile(fn): - print "truck file not found: "+fn + print "truck file not found: " + fn return p = rorparser() p.parse(fn) Modified: trunk/rortoolkit.bat =================================================================== --- trunk/rortoolkit.bat 2007-06-25 18:04:46 UTC (rev 27) +++ trunk/rortoolkit.bat 2007-06-25 20:17:24 UTC (rev 28) @@ -1 +1 @@ -C:\python25\python.exe rortoolkit.py %1 %2 %3 %4 %5 %6 %7 %8 %9 +%systemdrive%\python25\python.exe rortoolkit.py %1 %2 %3 %4 %5 %6 %7 %8 %9 Modified: trunk/terraineditor.bat =================================================================== --- trunk/terraineditor.bat 2007-06-25 18:04:46 UTC (rev 27) +++ trunk/terraineditor.bat 2007-06-25 20:17:24 UTC (rev 28) @@ -1 +1 @@ -C:\python25\python.exe terraineditor.py %1 %2 %3 %4 %5 %6 %7 %8 %9 +%systemdrive%\python25\python.exe terraineditor.py %1 %2 %3 %4 %5 %6 %7 %8 %9 Modified: trunk/truckeditor.bat =================================================================== --- trunk/truckeditor.bat 2007-06-25 18:04:46 UTC (rev 27) +++ trunk/truckeditor.bat 2007-06-25 20:17:24 UTC (rev 28) @@ -1 +1 @@ -C:\python25\python.exe truckeditor.py %1 %2 %3 %4 %5 %6 %7 %8 %9 +%systemdrive%\python25\python.exe truckeditor.py %1 %2 %3 %4 %5 %6 %7 %8 %9 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-06-28 04:42:26
|
Revision: 35 http://roreditor.svn.sourceforge.net/roreditor/?rev=35&view=rev Author: rorthomas Date: 2007-06-27 21:42:23 -0700 (Wed, 27 Jun 2007) Log Message: ----------- added svn libs Modified Paths: -------------- trunk/lib/rortruckeditor/RoRTruckOgreWindow.py trunk/rortoolkit.py Added Paths: ----------- trunk/lib/pysvn/ trunk/lib/pysvn/Examples/ trunk/lib/pysvn/Examples/Client/ trunk/lib/pysvn/Examples/Client/parse_datetime.py trunk/lib/pysvn/Examples/Client/svn_cmd.py trunk/lib/pysvn/LICENSE.txt trunk/lib/pysvn/__init__.py trunk/lib/pysvn/_pysvn_2_5.pyd trunk/lib/pysvn/intl3_svn.dll trunk/lib/pysvn/libapr.dll trunk/lib/pysvn/libapriconv.dll trunk/lib/pysvn/libaprutil.dll trunk/lib/pysvn/libdb43.dll trunk/lib/pysvn/libeay32.dll trunk/lib/pysvn/msvcp71.dll trunk/lib/pysvn/msvcr71.dll trunk/lib/pysvn/pysvn.html trunk/lib/pysvn/pysvn_prog_guide.html trunk/lib/pysvn/pysvn_prog_ref.html trunk/lib/pysvn/pysvn_prog_ref.js trunk/lib/pysvn/ssleay32.dll trunk/svn.bat trunk/svn.py Added: trunk/lib/pysvn/Examples/Client/parse_datetime.py =================================================================== --- trunk/lib/pysvn/Examples/Client/parse_datetime.py (rev 0) +++ trunk/lib/pysvn/Examples/Client/parse_datetime.py 2007-06-28 04:42:23 UTC (rev 35) @@ -0,0 +1,378 @@ +''' + ==================================================================== + Copyright (c) 2003-2006 Barry A Scott. All rights reserved. + + This software is licensed as described in the file LICENSE.txt, + which you should have received as part of this distribution. + + ==================================================================== +''' + +_debug_parse_time = 0 + +class DateTimeSyntaxError( Exception ): + def __init__( self, reason ): + Exception.__init__( self ) + self._reason = reason + + def reason( self ): + return self._reason + + def __str__( self ): + return self._reason + + +class DateSyntaxError( DateTimeSyntaxError ): + def __init__( self, reason ): + DateTimeSyntaxError.__init__( self, reason ) + +class TimeSyntaxError( DateTimeSyntaxError ): + def __init__( self, reason ): + DateTimeSyntaxError.__init__( self, reason ) + +def parse_time( time_string ): + """parse_time( time_string ) + returns the UTC time represented by time_string + + british locale defaults used + + formats understood for a date are: + dayname - today, yesterday, monday, tuesday... + dd/mm/yy[yy] - numeric date + dd-mmm-yy[yy] - month as jan,feb,etc... + n units - n units of time ago + where units are: + seconds + minutes + hours + days + weeks + months + years + + + formats understood for time are: + HH:MM - absolute time in hours and minutes + HH:MM:SS - absolute time in hours, minutes and seconds + + formats understood for data and time are: + adate atime - absolute date followed by absolute time + rdate atime - relative date followed by absolute time + atime adate - absolute time followed by absolute date + atime rdate - absolute time followed by relative date + + """ + if _debug_parse_time: print '* parse_time: time_string=',time_string + + date = DateConversions() + + have_date = 0 + have_time = 0 + + table = string.maketrans("-/"," ") + + time_list = string.split( string.translate( time_string, table ) ) + + try: + day_time = convert_time( time_list[0] ) + time_list = time_list[1:] + if _debug_parse_time: + print '* parse_time: Time_list[0] is a time' + except TimeSyntaxError: + try: + day_time = convert_time( time_list[-1] ) + time_list = time_list[:-1] + if _debug_parse_time: + print '* parse_time: Time_list[-1] is a time' + except TimeSyntaxError: + day_time = 0 + + if len(time_list) == 0: + # default to today at time + result = date.midnight + day_time + if _debug_parse_time: print '* parse_time: 1 return',format_time(result) + return result + + match_type = date.numeric_type + matches = [] + for word in time_list: + day_matches = date.findMatchingDateName( word ) + if len(day_matches) == 0: + raise DateSyntaxError, "%s unknown date word" % word + + if date.isAmbiguous( day_matches ): + raise DateSyntaxError, date.reportAmbiguity( word, day_matches ) + + this_type = date.typeOfMatch( day_matches ) + if this_type != date.numeric_type: + if match_type == date.numeric_type: + match_type = this_type + elif match_type != this_type: + raise DateSyntaxError, "ambiguous mix of unit and month names" + + matches.append( day_matches[0] ) + if _debug_parse_time: print '* parse_time: matches=',matches + + if match_type == date.day_type: + if len(matches) != 1: + raise DateSyntaxError, "too many day words" + + day_matches = matches[0] + + result = date.convertDay( day_matches[2] ) + day_time + if _debug_parse_time: print '* parse_time: 2 return',format_time(result) + return result + + if match_type == date.unit_type: + # expect a set of pair of <num> <unit> + if _debug_parse_time >= 2: + print 'matches',matches + if (len(matches)&1) == 1: + raise DateSyntaxError, 'must have an even number parameters when using time units' + + time_offset = 0 + for index in range( 0, len(matches), 2 ): + value_tuple = matches[index] + unit_tuple = matches[index+1] + + if value_tuple[1] != date.numeric_type: + raise DateSyntaxError, 'Expecting a number of units' + if unit_tuple[1] != date.unit_type: + raise DateSyntaxError, 'Expecting a unit name' + + value = value_tuple[2] + unit = unit_tuple[2] + time_offset = time_offset + value*unit + + result = date.now - time_offset + if _debug_parse_time: print '* parse_time: 3 return',format_time(result) + return result + + if match_type == date.month_type: + # absolute date + if len(matches) < 1 or len(matches) > 3: + raise DateSyntaxError, 'too many date parts' + + day = -1 + month = -1 + year = -1 + + num_month_types = 0 + for entry in matches: + if date.isMonth( entry ): + num_month_types = num_month_types + 1 + + if num_month_types != 1: + raise DateSyntaxError,'too many months in the date string' + + + if date.isMonth( matches[0] ): + month = matches[0][2] + day = matches[1][2] + if len(matches) == 3: + year = matches[2][2] + else: + day = matches[0][2] + if matches[1][1] != date.month_type: + raise DateSyntaxError,'expecting month as first or second part of date' + month = matches[1][2] + if len(matches) == 3: + year = matches[2][2] + + seconds = day_time%60 + minutes = (day_time/60)%60 + hours = day_time/60/60 + + result = date.absDate( day, month, year, hours, minutes, seconds ) + if _debug_parse_time: print '* parse_time: 4 return',format_time(result) + return result + + if match_type == date.numeric_type and len(matches) == 3: + # assume its in locale order - which is assumed to be D M Y + day = matches[0][2] + month = matches[1][2] + year = matches[2][2] + + seconds = day_time%60 + minutes = (day_time/60)%60 + hours = day_time/60/60 + + result = date.absDate( day, month, year, hours, minutes, seconds ) + if _debug_parse_time: print '* parse_time: 4 return',format_time(result) + return result + + raise DateSyntaxError,'cannot understand date and time string ' + time_string + + +def convert_time( time_str ): + time_list = string.split( time_str, ':' ) + if len(time_list) < 2: + # not a time - no ":" + raise TimeSyntaxError, "Not a time" + + if len(time_list) > 3: + raise TimeSyntaxError, "Too many time parts" + + hour = time_list[0] + minute = time_list[1] + second = '0' + if len(time_list) > 2: + second = time_list[2] + + try: + hour = string.atoi( hour ) + minute = string.atoi( minute ) + second = string.atoi( second ) + except: + return -1 + + if( hour < 0 or hour > 23 ): + raise TimeSyntaxError, "hour value of %d invalid" % hour + if( minute < 0 or minute > 59 ): + raise TimeSyntaxError, "minutes value of %d invalid" % hour + if( second < 0 or second > 59 ): + raise TimeSyntaxError, "seconds value of %d invalid" % hour + + day_time = (hour*60 + minute)*60 + second + + return day_time + + +class DateConversions: + seconds_in_one_day = 24*60*60 + + day_type = 1 + month_type = 2 + unit_type = 3 + numeric_type = 4 + + date_names = [ + # day names + ('today', day_type, 0), + ('yesterday', day_type, -1), + ('monday', day_type, 1), + ('tuesday', day_type, 2), + ('wednesday', day_type, 3), + ('thursday', day_type, 4), + ('friday', day_type, 5), + ('saturday', day_type, 6), + ('sunday', day_type, 7), + # month names + ('january', month_type, 1), + ('feburary', month_type, 2), + ('march', month_type, 3), + ('april', month_type, 4), + ('may', month_type, 5), + ('june', month_type, 6), + ('july', month_type, 7), + ('august', month_type, 8), + ('september', month_type, 9), + ('october', month_type, 10), + ('november', month_type, 11), + ('december', month_type, 12), + # unit names + ('seconds', unit_type, 1), + ('minutes', unit_type, 60), + ('hours', unit_type, 60*60), + ('days', unit_type, 24*60*60.), + ('weeks', unit_type, 7*24*60*60), + ('months', unit_type, 30*24*60*60), + ('years', unit_type, 365*24*60*60) + ] + + def __init__( self ): + self.now = time.time() + self.year, self.month, self.day, self.hour, self.minute, self.second, self.weekday, self.julian, self.dst = time.localtime( self.now ) + + self.midnight = time.mktime( + (self.year, self.month, self.day, + 0, 0, 0, + self.weekday, self.julian, self.dst) ) + + def convertDay( self, day_offset ): + if day_offset == 0: # today + return self.midnight + elif day_offset == -1: # yesterday + return self.midnight - self.seconds_in_one_day + else: + # day of week + offset = day_offset - self.weekday - 1 + # make sure its in the past + if offset >= 0: + offset = offset - 7 + + return self.midnight + offset*self.seconds_in_one_day + + def absDate( self, day, month, year, hour=0, minute=0, second=0 ): + future_check = 0 + if year < 0: + year = self.year + future_check = 1 + elif year < 70: + year = year + 2000 + elif year < 100: + year = year + 1900 + + + try: + date = time.mktime( + (year, month, day, + hour, minute, second, + self.weekday, self.julian, -1) ) + except OverflowError: + raise DateSyntaxError,'cannot convert date and time year=%d/month=%d/day=%d %d:%d:%d' % ( + year, month, day, hour, minute, second ) + + if date > self.now and future_check: + year = year - 1 + + try: + date = time.mktime( + (year, month, day, + hour, minute, second, + self.weekday, self.julian, -1) ) + except OverflowError: + raise DateSyntaxError,'cannot convert date and time %d/%d/%d %d:%d:%d' % ( + year, month, day, hour, minute, second ) + + return date + + def findMatchingDateName( self, name ): + try: + value = string.atoi( name ) + return [(name, self.numeric_type, value )] + except: + pass + + matches = [] + name_len = len(name) + for entry in self.date_names: + entry_name = entry[0] + if len(entry_name) >= name_len and entry_name[0:name_len] == name: + matches.append( entry ) + + return matches + + + def typeOfMatch( self, matches ): + return matches[0][1] + + def isAmbiguous( self, matches ): + return len(matches) > 1 + + def isDay( self, matches ): + return matches[1] == self.day_type + + def isMonth( self, matches ): + return matches[1] == self.month_type + + def isUnit( self, matches ): + return matches[1] == self.unit_type + + def isNumeric( self, matches ): + return matches[1] == self.numeric_type + + def reportAmbiguity( self, name, tuples ): + names = map( lambda t: t[0], tuples ) + return "%s is ambiguous, it matches: %s" % (name, string.join( names, ', ' )) + Added: trunk/lib/pysvn/Examples/Client/svn_cmd.py =================================================================== --- trunk/lib/pysvn/Examples/Client/svn_cmd.py (rev 0) +++ trunk/lib/pysvn/Examples/Client/svn_cmd.py 2007-06-28 04:42:23 UTC (rev 35) @@ -0,0 +1,1123 @@ +''' + ==================================================================== + Copyright (c) 2003-2006 Barry A Scott. All rights reserved. + + This software is licensed as described in the file LICENSE.txt, + which you should have received as part of this distribution. + + ==================================================================== +''' +import pysvn +import time +import sys +import os +import parse_datetime +import glob +import locale + +class CommandError( Exception ): + def __init__( self, reason ): + Exception.__init__( self ) + self._reason = reason + + def reason( self ): + return self._reason + + def __str__( self ): + return self._reason + +def main( args ): + progname = os.path.basename( args[0] ) + pause = False + if args[1:2] == ['--pause']: + del args[1] + pause = True + + # if the locale is not setup SVN can report errors handling non ascii file names + initLocale() + + svn_cmd = SvnCommand( progname ) + rc = svn_cmd.dispatch( args[1:] ) + if pause: + sys.stdin.readline() + return rc + +def initLocale(): + # init the locale + if sys.platform == 'win32': + locale.setlocale( locale.LC_ALL, '' ) + + else: + language_code, encoding = locale.getdefaultlocale() + if language_code is None: + language_code = 'en_GB' + + if encoding is None: + encoding = 'UTF-8' + if encoding.lower() == 'utf': + encoding = 'UTF-8' + + try: + # setlocale fails when params it does not understand are passed + locale.setlocale( locale.LC_ALL, '%s.%s' % (language_code, encoding) ) + except locale.Error: + # force a locale that will work + locale.setlocale( locale.LC_ALL, 'en_GB.UTF-8' ) + +def fmtDateTime( t ): + return time.strftime( '%d-%b-%Y %H:%M:%S', time.localtime( t ) ) + +wc_status_kind_map = { +pysvn.wc_status_kind.added: 'A', +pysvn.wc_status_kind.conflicted: 'C', +pysvn.wc_status_kind.deleted: 'D', +pysvn.wc_status_kind.external: 'X', +pysvn.wc_status_kind.ignored: 'I', +pysvn.wc_status_kind.incomplete: '!', +pysvn.wc_status_kind.missing: '!', +pysvn.wc_status_kind.merged: 'G', +pysvn.wc_status_kind.modified: 'M', +pysvn.wc_status_kind.none: ' ', +pysvn.wc_status_kind.normal: ' ', +pysvn.wc_status_kind.obstructed: '~', +pysvn.wc_status_kind.replaced: 'R', +pysvn.wc_status_kind.unversioned: '?', +} + +wc_notify_action_map = { +pysvn.wc_notify_action.add: 'A', +pysvn.wc_notify_action.commit_added: 'A', +pysvn.wc_notify_action.commit_deleted: 'D', +pysvn.wc_notify_action.commit_modified: 'M', +pysvn.wc_notify_action.commit_postfix_txdelta: None, +pysvn.wc_notify_action.commit_replaced: 'R', +pysvn.wc_notify_action.copy: 'c', +pysvn.wc_notify_action.delete: 'D', +pysvn.wc_notify_action.failed_revert: 'F', +pysvn.wc_notify_action.resolved: 'R', +pysvn.wc_notify_action.restore: 'R', +pysvn.wc_notify_action.revert: 'R', +pysvn.wc_notify_action.skip: 'skip', +pysvn.wc_notify_action.status_completed: None, +pysvn.wc_notify_action.status_external: 'X', +pysvn.wc_notify_action.update_add: 'A', +pysvn.wc_notify_action.update_completed: None, +pysvn.wc_notify_action.update_delete: 'D', +pysvn.wc_notify_action.update_external: 'X', +pysvn.wc_notify_action.update_update: 'U', +pysvn.wc_notify_action.annotate_revision: 'A', +} +if hasattr( pysvn.wc_notify_action, 'locked' ): + wc_notify_action_map[ pysvn.wc_notify_action.locked ] = 'locked' + wc_notify_action_map[ pysvn.wc_notify_action.unlocked ] = 'unlocked' + wc_notify_action_map[ pysvn.wc_notify_action.failed_lock ] = 'failed_lock' + wc_notify_action_map[ pysvn.wc_notify_action.failed_unlock ] = 'failed_unlock' + + +class SvnCommand: + def __init__( self, progname ): + self.progname = progname + self.client = None + self.revision_update_complete = None + self.notify_message_list = [] + self.pysvn_testing = False + self.debug_enabled = False + + def debug( self, msg, args=() ): + if self.debug_enabled: + print 'Debug:', msg % args + + def initClient( self, config_dir ): + self.client = pysvn.Client( config_dir ) + self.client.exception_style = 1 + self.client.callback_get_login = self.callback_getLogin + self.client.callback_get_log_message = self.callback_getLogMessage + self.client.callback_notify = self.callback_notify + self.client.callback_cancel = self.callback_cancel + self.client.callback_ssl_client_cert_password_prompt = self.callback_ssl_client_cert_password_prompt + self.client.callback_ssl_client_cert_prompt = self.callback_ssl_client_cert_prompt + self.client.callback_ssl_server_prompt = self.callback_ssl_server_prompt + self.client.callback_ssl_server_trust_prompt = self.callback_ssl_server_trust_prompt + + def callback_ssl_client_cert_password_prompt( self ): + print 'callback_ssl_client_cert_password_prompt' + + def callback_ssl_client_cert_prompt( self ): + print 'callback_ssl_client_cert_prompt' + + def callback_ssl_server_prompt( self ): + print 'callback_ssl_server_prompt' + + def callback_ssl_server_trust_prompt( self, trust_data ): + for key,value in trust_data.items(): + print '%s: %s' % (key, value) + print + answer = '' + while answer.lower() not in ['p','t','r']: + sys.stdout.write( '(P)ermanent accept, (T)emporary accept or (R)eject: ' ) + answer = sys.stdin.readline().strip() + if answer.lower() == 'p': + return True, trust_data['failures'], True + if answer.lower() == 't': + return True, trust_data['failures'], False + return False, 0, False + + def callback_cancel( self ): + return False + + def callback_notify( self, arg_dict ): + if arg_dict['action'] == pysvn.wc_notify_action.update_completed: + self.revision_update_complete = arg_dict['revision'] + elif arg_dict['path'] != '' and wc_notify_action_map[ arg_dict['action'] ] is not None: + msg = '%s %s' % (wc_notify_action_map[ arg_dict['action'] ], arg_dict['path']) + if self.pysvn_testing != '99.99.99': + self.notify_message_list.append( msg ) + else: + print msg + + def callback_getLogin( self, realm, username, may_save ): + print 'May save:',may_save + print 'Realm:',realm + if username: + print 'Username:',username + else: + sys.stdout.write( 'Username: ' ) + username = sys.stdin.readline().strip() + if len(username) == 0: + return 0, '', '', False + + sys.stdout.write( 'Password: ' ) + password = sys.stdin.readline().strip() + + save_password = 'x' + while save_password.lower() not in ['y','ye','yes','n', 'no','']: + sys.stdout.write( 'Save password? [y/n] ' ) + save_password = sys.stdin.readline().strip() + + return 1, username, password, save_password in ['y','ye','yes'] + + def getLogMessage( self ): + sys.stdout.write( 'Log message\n' ) + sys.stdout.write( '--- -------\n' ) + message = sys.stdin.read() + return message + + def callback_getLogMessage( self ): + return True, self.getLogMessage() + + def dispatch( self, argv ): + try: + args = SvnArguments( argv ) + cmd_name = 'cmd_%s' % args.getCommandName( 'help' ) + + self.initClient( args.getOptionalValue( '--config-dir', '' ) ) + self.client.set_auth_cache( args.getBooleanOption( '--no-auth-cache', False ) ) + self.pysvn_testing = args.getOptionalValue( '--pysvn-testing', '99.99.99' ) + self.debug_enabled = args.getBooleanOption( '--debug', True ) + + getattr( self, cmd_name, self.cmd_help )( args ) + + self.printNotifyMessages() + + except pysvn.ClientError, e: + self.printNotifyMessages() + print e.args[0] + return 1 + except CommandError, e: + self.printNotifyMessages() + print e.reason() + return 1 + + return 0 + + def printNotifyMessages( self ): + # different versions of SVN notify messages in different orders + # by sorting before printing we hope to have one set of regression + # test data for multiple versions of SVN + self.notify_message_list.sort() + for msg in self.notify_message_list: + print msg + self.notify_message_list = [] + + def cmd_version( self, args ): + print 'PYSVN Version:',pysvn.version + print 'SVN Version:',pysvn.svn_version + if hasattr( pysvn, 'svn_api_version' ): + print 'SVN API Version:',pysvn.svn_api_version + print 'pysvn._pysvn',pysvn._pysvn + + + def cmd_is_url( self, args ): + path = args.getPositionalArgs( 1 )[0] + is_url = self.client.is_url( path ) + if is_url: + print 'url',path + else: + print 'path',path + + def cmd_add( self, args ): + recurse = args.getBooleanOption( '--non-recursive', False ) + force = args.getBooleanOption( '--force', False ) + + self.client.add( args.getPositionalArgs( 1 ), recurse=recurse, force=force ) + + def cmd_annotate( self, args ): + start_revision, end_revision = args.getOptionalRevisionPair( '--revision', '0', 'head' ) + positional_args = args.getPositionalArgs( 1, 1 ) + all_lines = self.client.annotate( positional_args[0], + revision_start=start_revision, + revision_end=end_revision ) + self.printNotifyMessages() + + for line in all_lines: + print '%d| r%d | %s | %s | %s' % \ + (line['number'], + line['revision'].number, + line['author'], + line['date'], + line['line']) + cmd_ann = cmd_annotate + + def cmd_cat( self, args ): + revision = args.getOptionalRevision( '--revision', 'head' ) + text = self.client.cat( args.getPositionalArgs( 1, 1 )[0], revision=revision ) + print text + + def cmd_checkout( self, args ): + recurse = args.getBooleanOption( '--non-recursive', False ) + positional_args = args.getPositionalArgs( 1, 2 ) + if len(positional_args) == 1: + positional_args.append( os.path.basename( positional_args[0] ) ) + + self.revision_update_complete = None + self.client.checkout( positional_args[0], positional_args[1], recurse=recurse ) + self.printNotifyMessages() + + if self.revision_update_complete is not None: + print 'Checked out revision',self.revision_update_complete.number + else: + print 'Checked out unknown revision - checkout failed?' + + cmd_co = cmd_checkout + + def cmd_cleanup( self, args ): + positional_args = args.getPositionalArgs( 0, 1 ) + if len(positional_args) == 0: + positional_args.append( '.' ) + + self.client.cleanup( positional_args[0] ) + + def cmd_checkin( self, args ): + msg = args.getOptionalValue( '--message', '' ) + + recurse = args.getBooleanOption( '--non-recursive', False ) + positional_args = args.getPositionalArgs( 0 ) + if len(positional_args) == 0: + positional_args.append( '.' ) + if msg == '': + msg = self.getLogMessage() + + rev = self.client.checkin( positional_args, msg, recurse=recurse ) + self.printNotifyMessages() + + if rev is None: + print 'Nothing to commit' + elif rev.number > 0: + print 'Revision',rev.number + else: + print 'Commit failed' + + cmd_commit = cmd_checkin + cmd_ci = cmd_checkin + + def cmd_copy( self, args ): + positional_args = args.getPositionalArgs( 2, 2 ) + self.client.copy( positional_args[0], positional_args[1] ) + cmd_cp = cmd_copy + + def cmd_diff( self, args ): + recurse = args.getBooleanOption( '--non-recursive', False ) + revision1, revision2 = args.getOptionalRevisionPair( '--revision', 'base', 'working' ) + positional_args = args.getPositionalArgs( 0, 1 ) + if len(positional_args) == 0: + positional_args.append( '.' ) + + if os.environ.has_key('TEMP'): + tmpdir = os.environ['TEMP'] + elif os.environ.has_key('TMPDIR'): + tmpdir = os.environ['TMPDIR'] + elif os.environ.has_key('TMP'): + tmpdir = os.environ['TMP'] + elif os.path.exists( '/usr/tmp' ): + tmpdir = '/usr/tmp' + elif os.path.exists( '/tmp' ): + tmpdir = '/tmp' + else: + print 'No tmp dir!' + return + + tmpdir = os.path.join( tmpdir, 'svn_tmp' ) + self.debug( 'cmd_diff %r, %r, %r, %r, %r' % (tmpdir, positional_args[0], recurse, revision1, revision2) ) + diff_text = self.client.diff( tmpdir, positional_args[0], recurse=recurse, + revision1=revision1, revision2=revision2, + diff_options=['-u'] ) + print diff_text.encode('utf-8') + + def cmd_export( self, args ): + force = args.getBooleanOption( '--force', False ) + revision_url = args.getOptionalRevision( '--revision', 'head' ) + revision_wc = args.getOptionalRevision( '--revision', 'working' ) + native_eol = args.getOptionalValue( '--native-eol', None ) + positional_args = args.getPositionalArgs( 2, 2 ) + if self.client.is_url( positional_args[0] ): + revision = revision_url + else: + revision = revision_wc + + self.client.export( positional_args[0], positional_args[1], revision=revision, force=force, native_eol=native_eol ) + + def cmd_info( self, args ): + positional_args = args.getPositionalArgs( 0, 1 ) + if len(positional_args) == 0: + positional_args.append( '.' ) + + path = positional_args[0] + + entry = self.client.info( path ) + + print 'Path:',path + if entry.name and entry.name != 'svn:this_dir': + print 'Name:',entry.name.encode('utf-8') + if entry.url: + print 'Url:',entry.url.encode('utf-8') + if entry.repos and self.pysvn_testing >= '01.03.00': + print 'Repository:',entry.repos + if entry.uuid: + print 'Repository UUID:',entry.uuid + if entry.revision.kind == pysvn.opt_revision_kind.number: + print 'Revision:',entry.revision.number + if entry.kind == pysvn.node_kind.file: + print 'Node kind: file' + elif entry.kind == pysvn.node_kind.dir: + print 'Node kind: directory' + elif entry.kind == pysvn.node_kind.none: + print 'Node kind: none' + else: + print 'Node kind: unknown' + + if entry.schedule == pysvn.wc_schedule.normal: + print "Schedule: normal" + elif entry.schedule == pysvn.wc_schedule.add: + print "Schedule: add" + elif entry.schedule == pysvn.wc_schedule.delete: + print "Schedule: delete" + elif entry.schedule == pysvn.wc_schedule.replace: + print "Schedule: replace" + if entry.is_copied: + if entry.copyfrom_url: + print 'Copied From URL:', entry.copyfrom_url.encode('utf-8') + if entry.copyfrom_rev.number: + print 'Copied From Rev:', entry.copyfrom_rev.number + if entry.commit_author: + print 'Last Changed Author:', entry.commit_author.encode('utf-8') + if entry.commit_revision.number: + print 'Last Changed Rev:', entry.commit_revision.number + if entry.commit_time: + print 'Last Changed Date:', fmtDateTime( entry.commit_time ) + if entry.text_time: + print 'Text Last Updated:', fmtDateTime( entry.text_time ) + if entry.properties_time and self.pysvn_testing == '99.99.99': + print 'Properties Last Updated:', fmtDateTime( entry.properties_time ) + if entry.checksum: + print 'Checksum:', entry.checksum + + def cmd_info2( self, args ): + recurse = args.getBooleanOption( '--recursive', True ) + revision_url = args.getOptionalRevision( '--revision', 'head' ) + revision_path = args.getOptionalRevision( '--revision', 'unspecified' ) + + positional_args = args.getPositionalArgs( 0, 1 ) + if len(positional_args) == 0: + positional_args.append( '.' ) + + path = positional_args[0] + + if self.client.is_url( path ): + revision = revision_url + else: + revision = revision_path + + all_entries = self.client.info2( path, revision=revision, recurse=recurse ) + + for path, info in all_entries: + print + print 'Path:',path.encode('utf-8') + + if info.URL: + print 'Url:',info.URL.encode('utf-8') + if info.rev: + print 'Revision:',info.rev.number + if info.repos_root_URL and self.pysvn_testing >= '01.03.00': + print 'Repository root URL:',info.repos_root_URL + if info.repos_UUID: + print 'Repository UUID:',info.repos_UUID + if info.last_changed_author: + print 'Last changed author:',info.last_changed_author.encode('utf-8') + if info.last_changed_date: + print 'Last Changed Date:', fmtDateTime( info.last_changed_date ) + if info.last_changed_rev.kind == pysvn.opt_revision_kind.number: + print 'Last changed revision:',info.last_changed_rev.number + if info.kind == pysvn.node_kind.file: + print 'Node kind: file' + elif info.kind == pysvn.node_kind.dir: + print 'Node kind: directory' + elif info.kind == pysvn.node_kind.none: + print 'Node kind: none' + else: + print 'Node kind: unknown' + if info.lock: + print 'Lock Owner:',info.lock.owner.encode('utf-8') + print 'Lock Creation Date:',fmtDateTime( info.lock.creation_date ) + if info.lock.expiration_date is not None: + print 'Lock Expiration Date:',fmtDateTime( info.lock.expiration_date ) + print 'Lock Token:',info.lock.token + print 'Lock Comment:' + if info.lock.comment not in ['', None]: + print info.lock.comment + if info.wc_info: + wc_info = info.wc_info + if wc_info.schedule == pysvn.wc_schedule.normal: + print "Schedule: normal" + elif wc_info.schedule == pysvn.wc_schedule.add: + print "Schedule: add" + elif wc_info.schedule == pysvn.wc_schedule.delete: + print "Schedule: delete" + elif wc_info.schedule == pysvn.wc_schedule.replace: + print "Schedule: replace" + if wc_info.copyfrom_url: + print 'Copied From URL:', wc_info.copyfrom_url.encode('utf-8') + print 'Copied From Rev:', wc_info.copyfrom_rev.number + if wc_info.text_time: + print 'Text Last Updated:', fmtDateTime( wc_info.text_time ) + if wc_info.prop_time and self.pysvn_testing == '99.99.99': + print 'Properties Last Updated:', fmtDateTime( wc_info.prop_time ) + if wc_info.checksum: + print 'Checksum:', wc_info.checksum + + + def cmd_import( self, args ): + msg = self.getOptionalValue( '--message', '' ) + recurse = args.getBooleanOption( '--non-recursive', False ) + positional_args = args.getPositionalArgs( 2, 2 ) + self.client.import_( positional_args[0], positional_args[1], recurse=recurse ) + + def cmd_lock( self, args ): + msg = args.getOptionalValue( '--message', '' ) + force = args.getBooleanOption( '--force', True ) + positional_args = args.getPositionalArgs( 1, 1 ) + self.client.lock( positional_args[0], msg, force ); + + def cmd_log( self, args ): + start_revision, end_revision = args.getOptionalRevisionPair( '--revision', 'head', '0' ) + verbose = args.getBooleanOption( '--verbose', True ) + positional_args = args.getPositionalArgs( 1, 1 ) + all_logs = self.client.log( positional_args[0], + revision_start=start_revision, + revision_end=end_revision, + discover_changed_paths=verbose ) + + for log in all_logs: + print '-'*60 + print 'rev %d: %s | %s | %d lines' % \ + (log.revision.number, log.author, fmtDateTime( log.date ), + len(log.message.split('\n'))) + + if len(log.changed_paths) > 0: + print 'Changed paths:' + for change_info in log.changed_paths: + if change_info.copyfrom_path is None: + print ' %s %s' % (change_info.action, change_info.path) + else: + print ' %s %s (from %s:%d)' % \ + (change_info.action, change_info.path, + change_info.copyfrom_path, change_info.copyfrom_revision.number) + + print log.message + + print '-'*60 + + def cmd_ls( self, args ): + recurse = args.getBooleanOption( '--recursive', True ) + revision = args.getOptionalRevision( '--revision', 'head' ) + verbose = args.getBooleanOption( '--verbose', True ) + positional_args = args.getPositionalArgs( 0 ) + if len(positional_args) == 0: + positional_args.append( '.' ) + + for arg in positional_args: + all_files = self.client.ls( arg, revision=revision, recurse=recurse ) + if verbose: + for file in all_files: + args = {} + args.update( file ) + args['name'] = args['name'].encode('utf-8') + args['last_author'] = args['last_author'].encode('utf-8') + args['time_str'] = fmtDateTime( file.time ) + args['created_rev_num'] = file.created_rev.number + print '%(created_rev_num)7d %(last_author)-10s %(size)6d %(time_str)s %(name)s' % args + else: + for file in all_files: + print '%(name)s' % file + + def cmd_merge( self, args ): + recurse = args.getBooleanOption( '--recursive', True ) + dry_run = args.getBooleanOption( '--dry-run', False ) + notice_ancestry = args.getBooleanOption( '--notice-ancestry', False ) + + # need to figure out which variaty of the merge command this is + if args.haveOption( '--revision' ): + # its merge -r N:M SOURCE [WCPATH] + revision1, revision2 = args.getMandatoryRevisionPair( '--revision' ) + positional_args = args.getPositionalArgs( 1, 2 ) + if len(positional_args) == 1: + positional_args.append( '.' ) + path1 = positional_args[0] + path2 = positional_args[0] + wcpath = positional_args[1] + else: + # its merge sourceURL1[@N] sourceURL2[@M] [WCPATH] + positional_args = args.getPositionalArgs( 2, 3 ) + if len(positional_args) == 2: + positional_args.append( '.' ) + + path1, rev1 = self.parsePathWithRevision( positional_args[0] ) + path2, rev2 = self.parsePathWithRevision( positional_args[1] ) + wcpath = positional_args[2] + + + self.client.merge( path1, revision1, path2, revision2, wcpath, + recurse=recurse, dry_run=dry_run, notice_ancestry=notice_ancestry ) + + def cmd_mkdir( self, args ): + msg = args.getOptionalValue( '--message', '' ) + if msg == '': + msg = self.getLogMessage() + + self.client.mkdir( args.getPositionalArgs( 1, 1 )[0], msg ) + + def cmd_move( self, args ): + positional_args = args.getPositionalArgs( 2, 2 ) + self.client.move( positional_args[0], positional_args[1] ) + cmd_mv = cmd_move + + def props_by_path( self, a, b ): + return cmp( a[0], b[0] ) + + + def cmd_proplist( self, args ): + recurse = args.getBooleanOption( '--recursive', True ) + revision = args.getOptionalRevision( '--revision', 'working' ) + verbose = args.getBooleanOption( '--verbose', True ) + positional_args = args.getPositionalArgs( 0, 0 ) + if len(positional_args) == 0: + positional_args.append( '.' ) + + for arg in positional_args: + + if self.client.is_url( arg ): + revision = args.getOptionalRevision( '--revision', 'head' ) + + all_props = self.client.proplist( arg, revision=revision, recurse=recurse ) + all_props.sort( self.props_by_path ) + + for path, props in all_props: + print "Properties on '%s':" % path + prop_names = props.keys() + prop_names.sort() + for name in prop_names: + if verbose: + print ' %s: %s' % (name, props[name]) + else: + print ' %s' % name + + cmd_pl = cmd_proplist + + def cmd_propget( self, args ): + recurse = args.getBooleanOption( '--recursive', True ) + revision = args.getOptionalRevision( '--revision', 'working' ) + positional_args = args.getPositionalArgs( 1, 2 ) + if len(positional_args) == 1: + positional_args.append( '.' ) + if self.client.is_url( positional_args[0] ): + revision = args.getOptionalRevision( '--revision', 'head' ) + + props = self.client.propget( positional_args[0], positional_args[1], revision=revision, recurse=recurse ) + prop_names = props.keys() + prop_names.sort() + for name in prop_names: + print '%s: %s' % (name, props[name]) + + cmd_pg = cmd_propget + + def cmd_propset( self, args ): + recurse = args.getBooleanOption( '--recursive', True ) + revision = args.getOptionalRevision( '--revision', 'working' ) + verbose = args.getBooleanOption( '--verbose', True ) + positional_args = args.getPositionalArgs( 2, 3 ) + if len(positional_args) == 2: + positional_args.append( '.' ) + if self.client.is_url( positional_args[0] ): + revision = args.getOptionalRevision( '--revision', 'head' ) + + self.client.propset( positional_args[0], positional_args[1], positional_args[2], revision=revision, recurse=recurse ) + cmd_ps = cmd_propset + + def cmd_propdel( self, args ): + recurse = args.getBooleanOption( '--recursive', True ) + revision = args.getOptionalRevision( '--revision', 'working' ) + verbose = args.getBooleanOption( '--verbose', True ) + positional_args = args.getPositionalArgs( 1, 2 ) + if len(positional_args) == 1: + positional_args.append( '.' ) + if self.client.is_url( positional_args[0] ): + revision = args.getOptionalRevision( '--revision', 'head' ) + + self.client.propdel( positional_args[0], positional_args[1], revision=revision, recurse=recurse ) + cmd_pd = cmd_propdel + + def cmd_revproplist( self, args ): + revision = args.getOptionalRevision( '--revision', 'head' ) + verbose = args.getBooleanOption( '--verbose', False ) + positional_args = args.getPositionalArgs( 0, 1 ) + if len(positional_args) == 0: + positional_args.append( '.' ) + + rev, prop_dict = self.client.revproplist( positional_args[0], revision=revision ) + print 'Revision:',rev.number + prop_keys = prop_dict.keys() + prop_keys.sort() + for key in prop_keys: + print '%s: %s' % (key, prop_dict[ key ]) + + cmd_rpl = cmd_revproplist + + def cmd_revpropget( self, args ): + revision = args.getOptionalRevision( '--revision', 'head' ) + positional_args = args.getPositionalArgs( 1, 2 ) + if len(positional_args) == 1: + positional_args.append( '.' ) + + rev, value = self.client.revpropget( positional_args[0], positional_args[1], revision=revision ) + print 'Revision:',rev.number + print '%s: %s' % (positional_args[0], value) + + cmd_rpg = cmd_revpropget + + def cmd_revpropset( self, args ): + force = args.getBooleanOption( '--force', False ) + revision = args.getOptionalRevision( '--revision', 'head' ) + positional_args = args.getPositionalArgs( 2, 3 ) + if len(positional_args) == 2: + positional_args.append( '.' ) + + rev = self.client.revpropset( positional_args[0], positional_args[1], positional_args[2], revision=revision, force=force ) + cmd_rps = cmd_revpropset + + def cmd_revpropdel( self, args ): + force = args.getBooleanOption( '--force', False ) + revision = args.getOptionalRevision( '--revision', 'head' ) + positional_args = args.getPositionalArgs( 1, 2 ) + if len(positional_args) == 1: + positional_args.append( '.' ) + + self.client.revpropdel( positional_args[0], positional_args[1], revision=revision, force=force ) + cmd_rpd = cmd_revpropdel + + def cmd_remove( self, args ): + force = args.getBooleanOption( '--force', True ) + positional_args = args.getPositionalArgs( 1, 0 ) + self.client.remove( positional_args, force=force ) + cmd_rm = cmd_remove + + def cmd_resolved( self, args ): + recurse = args.getBooleanOption( '--recursive', True ) + positional_args = args.getPositionalArgs( 1, 1 ) + self.client.resolved( positional_args[0], recurse=recurse ) + + def cmd_revert( self, args ): + recurse = args.getBooleanOption( '--recursive', True ) + positional_args = args.getPositionalArgs( 1, 1 ) + self.client.revert( positional_args[0], recurse=recurse ) + + def by_path( self, a, b ): + return cmp( a.path, b.path ) + + def cmd_status( self, args ): + recurse = args.getBooleanOption( '--non-recursive', False ) + verbose = args.getBooleanOption( '--verbose', True ) + ignore = args.getBooleanOption( '--no-ignore', False ) + update = args.getBooleanOption( '--show-updates', True ) + + positional_args = args.getPositionalArgs( 0 ) + if len(positional_args) == 0: + all_files = self.client.status( '', recurse=recurse, get_all=verbose, ignore=ignore, update=update ) + self._cmd_status_print( all_files, verbose, update, ignore ) + else: + for arg in positional_args: + all_files = self.client.status( arg, recurse=recurse, get_all=verbose, ignore=ignore, update=update ) + self._cmd_status_print( all_files, verbose, update, ignore ) + + def _cmd_status_print( self, all_files, detailed, update, ignore ): + all_files.sort( self.by_path ) + for file in all_files: + if file.text_status == pysvn.wc_status_kind.ignored and ignore: + continue + + state = '%s%s%s%s%s' % (wc_status_kind_map[ file.text_status ], + wc_status_kind_map[ file.prop_status ], + ' L'[ file.is_locked ], + ' +'[ file.is_copied ], + ' S'[ file.is_switched ]) + + if( file.repos_text_status != pysvn.wc_status_kind.none + or file.repos_prop_status != pysvn.wc_status_kind.none ): + odd_status = '%s%s' % (wc_status_kind_map[ file.repos_text_status ], + wc_status_kind_map[ file.repos_prop_status ]) + else: + odd_status = ' ' + + lock_state = ' ' + if file.entry is not None and hasattr( file.entry, 'lock_token' ): + if file.entry.lock_token is not None: + lock_state = 'K' + + if hasattr( file, 'repos_lock' ) and file.repos_lock is not None: + lock_state = 'O' + + if file.entry is not None and detailed: + print '%s%s %s %6d %6d %-14s %s' % (state, lock_state, + odd_status, + file.entry.revision.number, + file.entry.commit_revision.number, + file.entry.commit_author.encode('utf-8'), + file.path.encode('utf-8')) + + elif detailed: + print '%s%s %s %6s %6s %-14s %s' % (state, lock_state, + odd_status, + '', + '', + '', + file.path.encode('utf-8')) + + elif update: + print '%s%s %s %s' % (state, lock_state, + odd_status, + file.path.encode('utf-8')) + + else: + if( file.text_status != pysvn.wc_status_kind.normal + or file.prop_status != pysvn.wc_status_kind.normal + or lock_state.strip() != ''): + print '%s%s %s' % (state, lock_state, file.path.encode('utf-8')) + + cmd_st = cmd_status + cmd_stat = cmd_status + + def cmd_switch( self, args ): + recurse = args.getBooleanOption( '--non-recursive', False ) + revision = args.getOptionalRevision( '--revision', 'head' ) + positional_args = args.getPositionalArgs( 1, 2 ) + if len(positional_args) == 1: + positional_args.append( '.' ) + self.client.switch( positional_args[0], positional_args[1], + recurse=recurse, revision=revision ) + + def cmd_relocate( self, args ): + recurse = args.getBooleanOption( '--non-recursive', False ) + positional_args = args.getPositionalArgs( 2, 3 ) + if len(positional_args) == 2: + positional_args.append( '.' ) + self.client.relocate( positional_args[0], positional_args[1], + positional_args[2], recurse=recurse ) + + def cmd_unlock( self, args ): + force = args.getBooleanOption( '--force', False ) + positional_args = args.getPositionalArgs( 1, 1 ) + self.client.unlock( positional_args[0], force ); + + def cmd_update( self, args ): + recurse = args.getBooleanOption( '--non-recursive', False ) + positional_args = args.getPositionalArgs( 0 ) + if len(positional_args) == 0: + positional_args.append( '.' ) + rev_list = self.client.update( positional_args[0], recurse=recurse ) + self.printNotifyMessages() + if type(rev_list) == type([]) and len(rev_list) != 1: + print 'rev_list = %r' % [rev.number for rev in rev_list] + + if self.revision_update_complete is not None: + print 'Updated to revision',self.revision_update_complete.number + else: + print 'Updated to unknown revision - update failed?' + + cmd_up = cmd_update + + def cmd_help( self, args ): + print 'Version: pysvn %d.%d.%d-%d' % pysvn.version,'svn %d.%d.%d-%s' % pysvn.svn_version + valid_cmd_names = [name for name in SvnCommand.__dict__.keys() if name.find('cmd_') == 0] + valid_cmd_names.sort() + print 'Available subcommands:' + index = 0 + for name in valid_cmd_names: + print ' %-12s' % name[4:], + if index % 4 == 3: + print + index += 1 + +# key is long option name, value is 1 if need next arg as value +long_opt_info = { + '--pause': 0, + + '--auto-props': 0, # enable automatic properties + '--config-dir': 1, # read user configuration files from directory ARG + '--diff-cmd': 1, # use ARG as diff command + '--diff3-cmd': 1, # use ARG as merge command + '--dry-run': 0, # try operation but make no changes + '--editor-cmd': 1, # use ARG as external editor + '--encoding': 1, # treat value as being in charset encoding ARG + '--force': 0, # force operation to run + '--force-log': 0, # force validity of log message source + '--incremental': 0, # give output suitable for concatenation + '--new': 1, # use ARG as the newer target + '--no-auth-cache': 0, # do not cache authentication tokens + '--no-auto-props': 0, # disable automatic properties + '--no-diff-deleted': 0, # do not print differences for deleted files + '--no-ignore': 0, # disregard default and svn:ignore property ignores + '--non-interactive': 0, # do no interactive prompting + '--notice-ancestry': 0, # notice ancestry when calculating differences + '--old': 1, # use ARG as the older target + '--password': 1, # specify a password ARG + '--relocate': 0, # relocate via URL-rewriting + '--revprop': 0, # operate on a revision property (use with -r) + '--strict': 0, # use strict semantics + '--targets': 1, # pass contents of file ARG as additional args + '--username': 1, # specify a username ARG + '--version': 0, # print client version info + '--xml': 0, # output in xml + '--file': 1, # read data from file ARG + '--native-eol': 1, # native eol ARG + '--non-recursive': 0, # operate on single directory only + '--recursive': 0, # descend recursively + '--message': 1, # specify commit message ARG + '--quiet': 0, # print as little as possible + '--revision': 1, # revision X or X:Y range. X or Y can be one of: + '--show-updates': 0, # display update information + '--verbose': 0, # print extra information + '--extensions': 1, # pass ARG as bundled options to GNU diff + '--pysvn-testing': 1, # modify behaviour to assist testing pysvn + '--debug': 0, # do debug stuff +} + +# map short name to long +short_opt_info = { + '-F': '--file', + '-N': '--non-recursive', + '-R': '--recursive', + '-m': '--message', + '-q': '--quiet', + '-r': '--revision', + '-u': '--show-updates', + '-v': '--verbose', + '-x': '--extensions', +} + + +# +# Usage: +# Construct with a commnad list +# call getCommandName() +# call getBooleanOption() and getOptionalValue() as needed +# finally call getPositionalArgs() +# +# +class SvnArguments: + def __init__( self, all_args ): + self.positional_args = [] + self.named_options = {} + self.used_named_options = {} + + need_next_arg = 0 + name = '' + + for arg in all_args: + if need_next_arg: + self.named_options[ name ] = arg + need_next_arg = 0 + + elif self._isOption( arg ): + name, need_next_arg = self._optionInfo( arg ) + if not need_next_arg: + self.named_options[ name ] = None + + else: + expanded_arg = glob.glob( arg ) + if len(expanded_arg) > 0: + self.positional_args.extend( expanded_arg ) + else: + self.positional_args.append( arg ) + if need_next_arg: + raise CommandError, 'Missing arg to option %s' % name + + def _isOption( self, arg ): + return arg[0] == '-' + + def _optionInfo( self, opt ): + # return long_name, arg_needed + long_opt = short_opt_info.get( opt, opt ) + if long_opt_info.has_key( long_opt ): + return long_opt, long_opt_info[ long_opt ] + raise CommandError, 'unknown option %s' % opt + + def _checkOptionsUsed( self ): + # check all options have been used + for opt_name in self.named_options.keys(): + if not self.used_named_options.has_key( opt_name ): + raise CommandError, 'unused option %s' % opt_name + + def parsePathWithRevision( self, path_rev, default_rev ): + if '@' in path_rev: + path = path_rev[:path_rev.find('@')] + rev = self._parseRevisionArg( path_rev[path_rev.find('@')+1:] ) + else: + path = path_rev + rev = self._parseRevisionArg( default_rev ) + return path, rev + + def _parseRevisionArg( self, rev_string ): + if rev_string.lower() == 'base': + return pysvn.Revision( pysvn.opt_revision_kind.base ) + if rev_string.lower() == 'head': + return pysvn.Revision( pysvn.opt_revision_kind.head ) + if rev_string.lower() == 'working': + return pysvn.Revision( pysvn.opt_revision_kind.working ) + if rev_string.lower() == 'committed': + return pysvn.Revision( pysvn.opt_revision_kind.committed ) + if rev_string.lower() == 'prev': + return pysvn.Revision( pysvn.opt_revision_kind.prev ) + if rev_string.lower() == 'unspecified': + return pysvn.Revision( pysvn.opt_revision_kind.unspecified ) + if rev_string[0] == '{' and rev_string[-1] == '}': + try: + date = parse_datetime.parse_time( rev_string[1:-2] ) + return pysvn.Revision( pysvn.opt_revision_kind.date, date ) + except parse_datetime.DateTimeSyntaxError, e: + raise CommandError, e.reason() + # either a rev number or a date + try: + return pysvn.Revision( pysvn.opt_revision_kind.number, int(rev_string) ) + except ValueError: + pass + raise CommandError, 'Cannot parse %s as a revision value' % rev_string + + + def _splitRevisionString( self, rev_string ): + # split the string at the first : that is not inside a {} pair + if rev_string[0] == '{': + # the : may be after the closing } + close_paren_index = rev_string.find( '}' ) + if close_paren_index == -1: + # error leave to others to report + return [rev_string] + + if close_paren_index == len(rev_string ): + # its just one revision + return [rev_string] + + if rev_string[close_paren_index+1] == ':': + return [rev_string[:close_paren_index+1], rev_string[close_paren_index+2:]] + + # another error case + return [rev_string] + else: + return rev_string.split(':',1) + + def getCommandName( self, default_command ): + if len(self.positional_args) > 0: + return self.positional_args.pop( 0 ) + else: + return default_command + + def haveOption( self, opt_name ): + return self.named_options.has_key( opt_name ) + + def getBooleanOption( self, opt_name, present_value=True ): + if self.named_options.has_key( opt_name ): + self.used_named_options[ opt_name ] = None + return present_value + else: + return not present_value + + def getOptionalValue( self, opt_name, default ): + if self.named_options.has_key( opt_name ): + self.used_named_options[ opt_name ] = None + return self.named_options[ opt_name ] + else: + return default + + def getOptionalRevision( self, opt_name, start_default ): + if self.named_options.has_key( opt_name ): + self.used_named_options[ opt_name ] = None + rev_string = self.named_options[ opt_name ] + + return self._parseRevisionArg( rev_string ) + else: + return self._parseRevisionArg( start_default ) + + def getMandatoryRevisionPair( self, opt_name ): + # parse a M:N or M as revision pair + if not self.named_options.has_key( opt_name ): + raise CommandError,'mandatory %s required' % opt_name + + self.used_named_options[ opt_name ] = None + + rev_strings = self._splitRevisionString( self.named_options[ opt_name ] ) + if len(rev_strings) == 1: + raise CommandError,'mandatory %s requires a pair of revisions' % opt_name + + return [self._parseRevisionArg( rev_strings[0] ), + self._parseRevisionArg( rev_strings[1] )] + + def getOptionalRevisionPair( self, opt_name, start_default, end_default=None ): + # parse a M:N or M as revision pair + if self.named_options.has_key( opt_name ): + self.used_named_options[ opt_name ] = None + rev_strings = self._splitRevisionString( self.named_options[ opt_name ] ) + if len(rev_strings) == 1: + if end_default is None: + # M means M:M + rev_strings.append( rev_strings[0] ) + else: + # M means M:end_default + rev_strings.append( end_default ) + + return [self._parseRevisionArg( rev_strings[0] ), + self._parseRevisionArg( rev_strings[1] )] + else: + return (self._parseRevisionArg( start_default ), + self._parseRevisionArg( end_default )) + + def getPositionalArgs( self, min_args, max_args=0 ): + # check min and max then return the list + if len(self.positional_args) < min_args: + raise CommandError, 'too few arguments - need atlease %d' % min_args + if max_args != 0 and len(self.positional_args) > max_args: + raise CommandError, 'too many arguments - need no more then %d' % max_args + + # as this is the last call on the args object we check the option where all used + self._checkOptionsUsed() + + return self.positional_args + +if __name__ == '__main__': + sys.exit( main( sys.argv ) ) Added: trunk/lib/pysvn/LICENSE.txt =================================================================== --- trunk/lib/pysvn/LICENSE.txt (rev 0) +++ trunk/lib/pysvn/LICENSE.txt 2007-06-28 04:42:23 UTC (rev 35) @@ -0,0 +1,47 @@ +================================================================= +Copyright (C) 2003-2006 Barry A. Scott. All rights reserved. + +================================================================= +The Apache Software License, Version 1.1 + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +3. The end-user documentation included with the redistribution, + if any, must include the following acknowledgment: + "This product includes software developed by + Barry A. Scott http://www.barrys-emacs.org." + Alternately, this acknowledgment may appear in the software itself, + if and wherever such third-party acknowledgments normally appear. + +4. The names "PySVN" must not be used to endorse or promote + products derived from this software without prior written + permission. For written permission, please contact + ba...@ba.... + +5. Products derived from this software may not be called "PySVN", + nor may "PySVN" appear in their name, without prior written + permission of Barry Scott. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL ... [truncated message content] |
From: <ror...@us...> - 2007-06-28 05:32:00
|
Revision: 41 http://roreditor.svn.sourceforge.net/roreditor/?rev=41&view=rev Author: rorthomas Date: 2007-06-27 22:31:59 -0700 (Wed, 27 Jun 2007) Log Message: ----------- updated svn implementation Modified Paths: -------------- trunk/lib/ror/starter.py Added Paths: ----------- trunk/lib/ror/svn.py Removed Paths: ------------- trunk/svn.bat trunk/svn.py Modified: trunk/lib/ror/starter.py =================================================================== --- trunk/lib/ror/starter.py 2007-06-28 05:26:35 UTC (rev 40) +++ trunk/lib/ror/starter.py 2007-06-28 05:31:59 UTC (rev 41) @@ -30,6 +30,9 @@ self.btnBugReport = wx.Button(self.panel, wx.ID_ANY, "Report a Bug") self.Bind(wx.EVT_BUTTON, self.OnBugReport, self.btnBugReport) + self.btnUpdate = wx.Button(self.panel, wx.ID_ANY, "Update") + self.Bind(wx.EVT_BUTTON, self.OnUpdate, self.btnUpdate) + self.btnExit = wx.Button(self.panel, wx.ID_ANY, "Exit") self.Bind(wx.EVT_BUTTON, self.OnExit, self.btnExit) @@ -55,8 +58,9 @@ self.__set_properties() self.__do_layout() + def OnUpdate(self, event=None): + - def OnStartRoR(self, event=None): #escape spaces! path = newpath.replace(" ", "\ ") Added: trunk/lib/ror/svn.py =================================================================== --- trunk/lib/ror/svn.py (rev 0) +++ trunk/lib/ror/svn.py 2007-06-28 05:31:59 UTC (rev 41) @@ -0,0 +1,53 @@ +#Thomas Fischer 28/06/2007, th...@th... +import sys, os, os.path + +URL = "http://roreditor.svn.sourceforge.net/svnroot/roreditor/trunk" +changes = 0 + +def notify(event_dict): + global changes + changes += 1 + #print event_dict + print str(event_dict['action']) + ", " + event_dict['path'] + +def getRevision(client, path): + info = client.info(path) + return info['revision'].number + +def svnupdate(): + global changes + path = os.path.dirname(os.path.abspath(__file__)) + try: + import pysvn + client = pysvn.Client() + revision_before = getRevision(client, path) + print "updating from revision %d ..." % revision_before + client.callback_notify = notify + client.update(path, + recurse = True, + revision = pysvn.Revision(pysvn.opt_revision_kind.head), + ignore_externals = False) + revision_after = getRevision(client, path) + print "updated to revision %d." % revision_after + if revision_before == revision_after and changes == 2: + print "already up to date!" + except: + print "error while checkout!" + +def svncheckout(): + print "checkout" + path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "svnco") + try: + import pysvn + client = pysvn.Client() + client.callback_notify = notify + client.checkout(URL, path) + except: + print "error while checkout!" + +def run(): + if os.path.isdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), "media")): + svnupdate() + else: + svncheckout() + Deleted: trunk/svn.bat =================================================================== --- trunk/svn.bat 2007-06-28 05:26:35 UTC (rev 40) +++ trunk/svn.bat 2007-06-28 05:31:59 UTC (rev 41) @@ -1 +0,0 @@ -%systemdrive%\python25\python.exe svn.py %1 %2 %3 %4 %5 %6 %7 %8 %9 Deleted: trunk/svn.py =================================================================== --- trunk/svn.py 2007-06-28 05:26:35 UTC (rev 40) +++ trunk/svn.py 2007-06-28 05:31:59 UTC (rev 41) @@ -1,59 +0,0 @@ -#Thomas Fischer 28/06/2007, th...@th... -import sys, os, os.path - -URL = "http://roreditor.svn.sourceforge.net/svnroot/roreditor/trunk" -changes = 0 - -def notify(event_dict): - global changes - changes += 1 - #print event_dict - print str(event_dict['action']) + ", " + event_dict['path'] - -def getRevision(client, path): - info = client.info(path) - return info['revision'].number - -def svnupdate(): - global changes - path = os.path.dirname(os.path.abspath(__file__)) - try: - import pysvn - client = pysvn.Client() - revision_before = getRevision(client, path) - print "updating from revision %d ..." % revision_before - client.callback_notify = notify - client.update(path, - recurse = True, - revision = pysvn.Revision(pysvn.opt_revision_kind.head), - ignore_externals = False) - revision_after = getRevision(client, path) - print "updated to revision %d." % revision_after - if revision_before == revision_after and changes == 2: - print "already up to date!" - except: - print "error while checkout!" - -def svncheckout(): - print "checkout" - path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "svnco") - try: - import pysvn - client = pysvn.Client() - client.callback_notify = notify - client.checkout(URL, path) - except: - print "error while checkout!" - -def run(): - if os.path.isdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), "media")): - svnupdate() - else: - svncheckout() - -def main(): - sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) - run() - -if __name__=="__main__": - main() \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-06-28 06:25:29
|
Revision: 48 http://roreditor.svn.sourceforge.net/roreditor/?rev=48&view=rev Author: rorthomas Date: 2007-06-27 23:25:28 -0700 (Wed, 27 Jun 2007) Log Message: ----------- * patched plugins.cfg Modified Paths: -------------- trunk/lib/ror/svn.py trunk/plugins.cfg Modified: trunk/lib/ror/svn.py =================================================================== --- trunk/lib/ror/svn.py 2007-06-28 06:15:07 UTC (rev 47) +++ trunk/lib/ror/svn.py 2007-06-28 06:25:28 UTC (rev 48) @@ -8,12 +8,12 @@ def getRootPath(): path = os.path.dirname(os.path.abspath(__file__)) if os.path.isdir(os.path.join(path, "media")): - print path return path path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"..\\..")) if os.path.isdir(os.path.join(path, "media")): - print path return path + # todo: throw exception! + return None def notify(event_dict): global changes Modified: trunk/plugins.cfg =================================================================== --- trunk/plugins.cfg 2007-06-28 06:15:07 UTC (rev 47) +++ trunk/plugins.cfg 2007-06-28 06:25:28 UTC (rev 48) @@ -1,7 +1,7 @@ PluginFolder=. Plugin=RenderSystem_GL.dll #disable the directx plugin as it would require the latest directx system -Plugin=RenderSystem_Direct3D9.dll +#Plugin=RenderSystem_Direct3D9.dll Plugin=Plugin_ParticleFX.dll Plugin=Plugin_BSPSceneManager.dll Plugin=Plugin_OctreeSceneManager.dll This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-06-28 06:45:22
|
Revision: 51 http://roreditor.svn.sourceforge.net/roreditor/?rev=51&view=rev Author: rorthomas Date: 2007-06-27 23:45:11 -0700 (Wed, 27 Jun 2007) Log Message: ----------- minor fixes Modified Paths: -------------- trunk/lib/ror/rorsettings.py trunk/setup.nsi Modified: trunk/lib/ror/rorsettings.py =================================================================== --- trunk/lib/ror/rorsettings.py 2007-06-28 06:39:35 UTC (rev 50) +++ trunk/lib/ror/rorsettings.py 2007-06-28 06:45:11 UTC (rev 51) @@ -10,7 +10,7 @@ class RoRSettings: rordir = None - configfilename = os.path.join(os.path.dirname(os.path.abspath(__file__)),"editor.cfg") + configfilename = os.path.join(os.path.dirname(os.path.abspath(__file__)), "editor.cfg") def __init__(self): self.LoadRoRDir() Modified: trunk/setup.nsi =================================================================== --- trunk/setup.nsi 2007-06-28 06:39:35 UTC (rev 50) +++ trunk/setup.nsi 2007-06-28 06:45:11 UTC (rev 51) @@ -2,7 +2,7 @@ ; HM NIS Edit Wizard helper defines !define PRODUCT_NAME "RoRToolkit" -!define PRODUCT_VERSION "0.0.5" +!define PRODUCT_VERSION "r50" !define PRODUCT_PUBLISHER "Thomas Fischer" !define PRODUCT_WEB_SITE "http://wiki.rigsofrods.com/index.php?title=RoRToolkit" !define PRODUCT_UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-06-28 06:48:38
|
Revision: 50 http://roreditor.svn.sourceforge.net/roreditor/?rev=50&view=rev Author: rorthomas Date: 2007-06-27 23:39:35 -0700 (Wed, 27 Jun 2007) Log Message: ----------- Modified Paths: -------------- trunk/lib/ror/rorsettings.py trunk/setup.nsi Modified: trunk/lib/ror/rorsettings.py =================================================================== --- trunk/lib/ror/rorsettings.py 2007-06-28 06:30:14 UTC (rev 49) +++ trunk/lib/ror/rorsettings.py 2007-06-28 06:39:35 UTC (rev 50) @@ -27,6 +27,7 @@ self.rordir = os.path.abspath(f.read()) f.close() print "Loaded RoR Directory: %s" % self.rordir + print "Loading..." except: print "error while loading rordir: %s" % self.configfilename Modified: trunk/setup.nsi =================================================================== --- trunk/setup.nsi 2007-06-28 06:30:14 UTC (rev 49) +++ trunk/setup.nsi 2007-06-28 06:39:35 UTC (rev 50) @@ -221,9 +221,8 @@ Section Uninstall Delete "$INSTDIR\${PRODUCT_NAME}.url" Delete "$INSTDIR\uninst.exe" - RMDir "/r" "$INSTDIR\media" - RMDir "/r" "$INSTDIR\lib" - Delete "$INSTDIR\*" + #RMDir "/r" "$INSTDIR\media" + RMDir "/r" "$INSTDIR" RMDir "/r" "$SMPROGRAMS\RoRToolkit" Delete "$STARTMENU.lnk" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-06-30 19:27:26
|
Revision: 70 http://roreditor.svn.sourceforge.net/roreditor/?rev=70&view=rev Author: rorthomas Date: 2007-06-30 12:27:23 -0700 (Sat, 30 Jun 2007) Log Message: ----------- * fixed wrong path issue when executing the other bat files Modified Paths: -------------- trunk/terraineditor.py trunk/truckeditor.py Modified: trunk/terraineditor.py =================================================================== --- trunk/terraineditor.py 2007-06-30 01:19:50 UTC (rev 69) +++ trunk/terraineditor.py 2007-06-30 19:27:23 UTC (rev 70) @@ -7,6 +7,11 @@ """ sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) + import ror.settingsManager + path = ror.settingsManager.getSettingsManager().getSetting("RigsOfRods", "BasePath") + if not os.path.isfile(os.path.join(path,"RoR.exe")): + import ror.starter + ror.starter.startApp() # Import Psyco if available try: Modified: trunk/truckeditor.py =================================================================== --- trunk/truckeditor.py 2007-06-30 01:19:50 UTC (rev 69) +++ trunk/truckeditor.py 2007-06-30 19:27:23 UTC (rev 70) @@ -7,6 +7,11 @@ """ sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) + import ror.settingsManager + path = ror.settingsManager.getSettingsManager().getSetting("RigsOfRods", "BasePath") + if not os.path.isfile(os.path.join(path,"RoR.exe")): + import ror.starter + ror.starter.startApp() # Import Psyco if available try: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-07-16 12:09:59
|
Revision: 105 http://roreditor.svn.sourceforge.net/roreditor/?rev=105&view=rev Author: rorthomas Date: 2007-07-16 05:09:58 -0700 (Mon, 16 Jul 2007) Log Message: ----------- * console updater now using gui * updated installer * minor improvements to svngui.py Modified Paths: -------------- trunk/lib/ror/svngui.py trunk/setup.nsi trunk/update.py Modified: trunk/lib/ror/svngui.py =================================================================== --- trunk/lib/ror/svngui.py 2007-07-16 05:59:08 UTC (rev 104) +++ trunk/lib/ror/svngui.py 2007-07-16 12:09:58 UTC (rev 105) @@ -12,10 +12,11 @@ import wx, os, os.path class svnUpdate(): - def __init__(self): + def __init__(self, restartApp=True): self.pr = wx.ProgressDialog("Updating ...", "Updating ...", style = wx.PD_SMOOTH | wx.PD_ELAPSED_TIME | wx.PD_ESTIMATED_TIME | wx.PD_REMAINING_TIME) self.pr.Show() self.changes = 0 + self.restartApp = restartApp svn.svnupdate(self.notify) self.showfinished() self.pr.Hide() @@ -34,10 +35,16 @@ dlg.ShowModal() dlg.Destroy() elif self.changes > 2: - dlg = wx.MessageDialog(self.pr, "Update finished!\nThe Application now restarts itself!", "Info", wx.OK | wx.ICON_INFORMATION) - dlg.ShowModal() - dlg.Destroy() - self.restart() + if self.restartApp: + dlg = wx.MessageDialog(self.pr, "Update finished!\nThe Application now restarts itself!", "Info", wx.OK | wx.ICON_INFORMATION) + dlg.ShowModal() + dlg.Destroy() + self.restart() + else: + dlg = wx.MessageDialog(self.pr, "Update finished!", "Info", wx.OK | wx.ICON_INFORMATION) + dlg.ShowModal() + dlg.Destroy() + def notify(self, event_dict): self.changes += 1 Modified: trunk/setup.nsi =================================================================== --- trunk/setup.nsi 2007-07-16 05:59:08 UTC (rev 104) +++ trunk/setup.nsi 2007-07-16 12:09:58 UTC (rev 105) @@ -47,9 +47,15 @@ ; Instfiles page !insertmacro MUI_PAGE_INSTFILES ; Finish page -!define MUI_FINISHPAGE_RUN "$INSTDIR\rortoolkit.bat" -!define MUI_FINISHPAGE_RUN_PARAMETERS "" +;!define MUI_FINISHPAGE_RUN "$INSTDIR\rortoolkit.bat" +;!define MUI_FINISHPAGE_RUN_PARAMETERS "" #!define MUI_FINISHPAGE_SHOWREADME "$INSTDIR\Example.file" + +!define MUI_FINISHPAGE_NOAUTOCLOSE +!define MUI_FINISHPAGE_RUN +!define MUI_FINISHPAGE_RUN_NOTCHECKED +!define MUI_FINISHPAGE_RUN_TEXT "Update and start (Can take some time)" +!define MUI_FINISHPAGE_RUN_FUNCTION "LaunchPostInstallation" !insertmacro MUI_PAGE_FINISH ; Uninstaller pages @@ -74,7 +80,8 @@ Name "${PRODUCT_NAME} ${PRODUCT_VERSION}" OutFile "RoRToolkitSetup.exe" -InstallDir "$PROGRAMFILES\RoRToolkit" +;InstallDir "$PROGRAMFILES\RoRToolkit" +InstallDir "c:\rortoolkit" ShowInstDetails show ShowUnInstDetails show @@ -160,7 +167,25 @@ Banner::destroy FunctionEnd +Function InstallPyParsing + InitPluginsDir + File /oname=$PLUGINSDIR\pyparsing-1.4.6.win32.exe "tools\pyparsing-1.4.6.win32.exe" + Banner::show /NOUNLOAD "Installing PyParsing Python Module ..." + ExecWait '"$PLUGINSDIR\pyparsing-1.4.6.win32.exe"' + Delete $PLUGINSDIR\pyparsing-1.4.6.win32.exe + Banner::destroy +FunctionEnd +Function InstallGraphViz + InitPluginsDir + File /oname=$PLUGINSDIR\graphviz-2.12.exe "tools\graphviz-2.12.exe" + Banner::show /NOUNLOAD "Installing Graphviz for Windows ..." + ExecWait '"$PLUGINSDIR\graphviz-2.12.exe"' + Delete $PLUGINSDIR\graphviz-2.12.exe + Banner::destroy +FunctionEnd + + Function .onInit InitPluginsDir File /oname=$PLUGINSDIR\splash.bmp "splash.bmp" @@ -174,20 +199,24 @@ Call CheckForPython SectionEnd -Section "Install DirectX" SEC02 +Section "Install Tools" SEC02 Call InstallDirectX -SectionEnd - -Section "Install PyWin32" SEC03 Call InstallPyWin32 + Call InstallPyParsing + Call InstallGraphViz SectionEnd -Section "Full Installation" SEC04 +Section "Full Installation" SEC03 SetOutPath "$INSTDIR" SetOverwrite try File "/r" "*" SectionEnd +Function "LaunchPostInstallation" + ExecWait '"$INSTDIR\update.bat"' + ExecWait '"$INSTDIR\rortoolkit.bat"' +FunctionEnd + Section -AdditionalIcons SetOutPath $INSTDIR WriteIniStr "$INSTDIR\${PRODUCT_NAME}.url" "InternetShortcut" "URL" "${PRODUCT_WEB_SITE}" Modified: trunk/update.py =================================================================== --- trunk/update.py 2007-07-16 05:59:08 UTC (rev 104) +++ trunk/update.py 2007-07-16 12:09:58 UTC (rev 105) @@ -2,8 +2,20 @@ def main(): sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) - import ror.svn - ror.svn.run() + guiVersion = True + if guiVersion: + import wx + + MainApp = wx.PySimpleApp(0) + wx.InitAllImageHandlers() #you may or may not need this + import ror.svngui + gui = ror.svngui.svnUpdate(False) + del gui + else: + #non-gui version: + import ror.svn + ror.svn.run() + if __name__=="__main__": main() \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-07-20 00:32:20
|
Revision: 109 http://roreditor.svn.sourceforge.net/roreditor/?rev=109&view=rev Author: rorthomas Date: 2007-07-19 17:31:37 -0700 (Thu, 19 Jul 2007) Log Message: ----------- * depchecker.py added groups * common: added UID function * starter: fixed graph and check rordir on startup * rewrote the terraineditor, mainly how the data is internally saved * ogremanager: now detects the renderer automatically Modified Paths: -------------- trunk/lib/ror/depchecker.py trunk/lib/ror/rorcommon.py trunk/lib/ror/starter.py trunk/lib/rorterraineditor/HelpFrame.py trunk/lib/rorterraineditor/MainFrame.py trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py trunk/lib/wxogre/OgreManager.py Added Paths: ----------- trunk/lib/ror/terrainparser.py trunk/terrainreadme.txt Removed Paths: ------------- trunk/readme.txt Modified: trunk/lib/ror/depchecker.py =================================================================== --- trunk/lib/ror/depchecker.py 2007-07-16 13:18:30 UTC (rev 108) +++ trunk/lib/ror/depchecker.py 2007-07-20 00:31:37 UTC (rev 109) @@ -169,16 +169,25 @@ else: if ext == ".truck": n.set('fillcolor', 'gold') + n.set('group', 'truck') elif ext == ".load": n.set('fillcolor', 'lightyellow') + n.set('group', 'load') elif ext == ".material": n.set('fillcolor', 'lightseagreen') + n.set('group', 'material') elif ext == ".terrn": n.set('fillcolor', 'forestgreen') + n.set('group', 'terrain') elif ext == ".mesh": n.set('fillcolor', 'lightsalmon') + n.set('group', 'mesh') + elif ext == ".odef": + n.set('fillcolor', 'lightsalmon') + n.set('group', 'object') elif ext == ".png" or ext == ".jpg" or ext == ".bmp": n.set('fillcolor', 'lightblue') + n.set('group', 'texture') @@ -335,10 +344,14 @@ sys.exit(0) def main(): + import settingsManager if len(sys.argv) < 3: usage() - if not os.path.isdir(sys.argv[1]): - print "%s is not a valid directory!" % sys.argv[1] + path = sys.argv[1] + if path.strip() == "rordir": + path = settingsManager.getSettingsManager().getSetting("RigsOfRods", "BasePath") + if not os.path.isdir(path): + print "%s is not a valid directory!" % path usage() if (len(sys.argv) == 3 and sys.argv[2] in ['all', 'missing', 'unused', 'md5sum']) or (len(sys.argv) == 4 and sys.argv[2] in ['dtree']): pass @@ -349,8 +362,7 @@ dependfilename = "" if len(sys.argv) == 4 and sys.argv[2] in ['dtree'] and sys.argv[3].strip() != "": dependfilename = sys.argv[3].strip() - - RoRDepChecker(sys.argv[1], sys.argv[2], dependfilename) + RoRDepChecker(path , sys.argv[2], dependfilename) if __name__ == "__main__": main() Modified: trunk/lib/ror/rorcommon.py =================================================================== --- trunk/lib/ror/rorcommon.py 2007-07-16 13:18:30 UTC (rev 108) +++ trunk/lib/ror/rorcommon.py 2007-07-20 00:31:37 UTC (rev 109) @@ -1,4 +1,5 @@ import wx +from random import Random def ShowOnAbout(event = None): rev = "" @@ -12,3 +13,27 @@ "About This", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() + + + +def randomID(num_bits=64): + """Return a string representing a bitfield num_bits long. + Maximum artbitrarily set to 1025""" + + if num_bits < 1: + raise RuntimeError,\ + "randomID called with negative (or zero) number of bits" + if num_bits > 1024: + raise RuntimeError,\ + "randomID called with too many bits (> 1024)" + + # create a num_bits string from random import Random + rnd = Random() + tmp_id = 0L + for i in range(0, num_bits): + tmp_id += long(rnd.randint(0,1)) << i + #rof + + # The 2: removes the '0x' and :-1 removes the L + rnd_id = hex(tmp_id)[2:-1] + return(rnd_id) \ No newline at end of file Modified: trunk/lib/ror/starter.py =================================================================== --- trunk/lib/ror/starter.py 2007-07-16 13:18:30 UTC (rev 108) +++ trunk/lib/ror/starter.py 2007-07-20 00:31:37 UTC (rev 109) @@ -68,7 +68,7 @@ self.Bind(wx.EVT_BUTTON, self.OnExit, self.btnExit) self.rordir = getSettingsManager().getSetting("RigsOfRods", "BasePath") - + self.checkRoRDir(self.rordir) #print self.rordir self.displayRoRDir() @@ -118,8 +118,8 @@ f.close() def OnDepGraph(self, event=None): - from depchecker import * - RoRDepChecker(self.rordir, "all", "") + import ror.depchecker + ror.depchecker.RoRDepChecker(self.rordir, "all", "") file = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..\\..\\dependencies.png")) print file if os.path.isfile(file): Added: trunk/lib/ror/terrainparser.py =================================================================== --- trunk/lib/ror/terrainparser.py (rev 0) +++ trunk/lib/ror/terrainparser.py 2007-07-20 00:31:37 UTC (rev 109) @@ -0,0 +1,291 @@ +import wx, os, os.path + +from logger import log +from settingsManager import getSettingsManager + +class Object: + x = None + y = None + z = None + rotx = None + roty = None + rotz = None + name = "" + filename = "" + additionaloptions = [] + comments = [] + mayRotate = True + + error = None + + def setPosition(self, x, y, z): + self.x = x + self.y = y + self.z = z + + def setRotation(self, x, y, z): + self.rotx = x + self.roty = y + self.rotz = z + + +class RoRTerrain: + filename = "" + TerrainName = "" + TerrainConfig = "" + filename = "" + comments = {} + + trucks = [] + loads = [] + objects = [] + + UsingCaelum = False + WaterHeight = None + SkyColor = None + SkyColorLine = None + TruckStartPosition = None + CameraStartPosition = None + CharacterStartPosition = None + + def saveFile(self, filename, lines): + f = open(filename, 'w') + f.writelines(lines) + f.close() + + def loadFile(self,filename): + f=open(filename, 'r') + content = f.readlines() + f.close() + return content + + def __init__(self, filename): + self.filename = filename + content = self.loadFile(filename) + log().info("processing terrain file: %s" % filename) + self.processTerrnFile(content) + self.FixTerrainConfig(os.path.join(os.path.dirname(filename), self.TerrainConfig)) + log().info("processing of terrain finished!") + + def FixTerrainConfig(self, filename): + content = self.loadFile(filename) + for i in range(0, len(content)): + if content[i].lower().find("maxpixelerror") >= 0: + content[i] = "MaxPixelError=0\n" + log().info("fixed terrain's MaxPixelError - error") + break + self.saveFile(filename, content) + + def processTerrnFile(self, content): + linecounter = 0 + comm = [] + for i in range(0, len(content)): + # convert tabs to spaces! + content[i] = content[i].replace("\t", " ") + + if content[i].strip() == "": + comm.append(content[i]) + continue + if content[i].strip()[0:4] == "////": + # ignore editor self made comments (usefull for those error msgs) + continue + if content[i].strip()[0:2] == "//": + comm.append(content[i]) + continue + if content[i].strip()[0:1] == ";": + # bugfix wrong characters! + comm.append(content[i].replace(";","//")) + continue + if content[i].strip().lower() == "end": + continue + + # do not count empty or comment lines! + linecounter += 1 + if linecounter == 1: + #terrain name + self.TerrainName = content[i].strip() + continue + elif linecounter == 2: + # .cfg file + self.TerrainConfig = content[i].strip() + continue + if content[i].strip()[0].lower() == "w": + self.WaterHeight = float(content[i].strip()[2:]) + continue + if content[i].strip().lower() == "caelum": + self.UsingCaelum = True + continue + if linecounter < 10 and len(content[i].split(",")) == 3: + # sky color + sc = content[i].split(",") + self.SkyColor = (float(sc[0]), float(sc[1]), float(sc[2])) + self.SkyColorLine = content[i] + continue + if linecounter < 10 and len(content[i].split(",")) == 9 or len(content[i].split(",")) == 6: + # spawning Position + sp = content[i].split(",") + self.TruckStartPosition = [float(sp[0]), float(sp[1]), float(sp[2])] + + self.CameraStartPosition = [float(sp[3]), float(sp[4]), float(sp[5])] + if len(sp) == 9: + self.CharacterStartPosition = [float(sp[6]), float(sp[7]), float(sp[8])] + continue + + arr = content[i].split(",") + try: + x = float(arr[0]) + y = float(arr[1]) + z = float(arr[2]) + rx = float(arr[3]) + ry = float(arr[4]) + rz = float(arr[5]) + objname = (arr[6]).strip().split(" ") + except: + log().error("unable to parse line: %s. ignoring it!" % content[i]) + continue + + #print objname + if objname[0][0:5].lower() == "truck" and len(objname) > 1: + truck = Object() + truck.name = "truck" + truck.filename = objname[-1].strip() + truck.comments = comm + comm = [] + truck.setPosition(x, y, z) + truck.setRotation(rx, ry, -rz) + truck.additionaloptions = objname[1:] + truck.mayRotate=False + self.trucks.append(truck) + continue + if objname[0][0:4] == "load" and len(objname) > 1: + load = Object() + load.name = "load" + load.filename = objname[-1].strip() + load.comments = comm + comm = [] + load.setPosition(x, y, z) + load.setRotation(rx, ry, -rz) + load.additionaloptions = objname[1:] + load.mayRotate=False + self.loads.append(load) + continue + + # now it can just be an static object + objectname = objname[0].strip() + obj = Object() + obj.name = objectname + obj.filename = objectname + obj.comments = comm + comm = [] + obj.setPosition(x, y, z) + obj.setRotation(rx, ry, rz) + obj.additionaloptions = objname[1:] + self.objects.append(obj) + + + + def loadOdef(self, objname): + try: + f=open(self.rordir+"\\data\\objects\\%s.odef" % (objname), 'r') + content = f.readlines() + f.close() + meshname = content[0].strip() + scalearr = content[1].split(",") + self.myODefs[objname] = [] + if len(content) > 2: + for i in range(1,len(content)): + line = content[i] + if line.lower().strip() == "end": + break + self.myODefs[objname].append(line.split(",")) + return (meshname, float(scalearr[0]), float(scalearr[1]), float(scalearr[2])) + else: + return (meshname, 1, 1, 1) + except Exception, err: + print "error while processing odef file of %s" % objname + print str(err) + + def getObjectLines(self, object): + lines = [] + + # add comments + if len(object.comments) > 0: + for comment in object.comments: + lines.append(comment) + + # construct objects name + objname = object.name + if len(object.additionaloptions) > 0: + tmp = (" " + " ".join(object.additionaloptions)).strip() + objname += " " + tmp + + # add line itself + linearray = [self.formatFloat(object.x), + self.formatFloat(object.y), + self.formatFloat(object.z), + self.formatFloat(object.rotx), + self.formatFloat(object.roty), + self.formatFloat(object.rotz), + objname] + line = ", ".join(linearray) + + if not object.error is None: + lines.append("//// the next object had errors, so the terraineditor commented it out:\n") + lines.append("//"+line.strip()+"\n") + else: + lines.append(line.strip()+"\n") + return lines + + def formatFloat(self, fl): + return "%12s" % ("%0.6f" % (float(fl))) + + + def save(self, filename = None): + if filename is None: + filename = self.filename + lines = [] + lines.append(self.TerrainName+"\n") + lines.append(self.TerrainConfig+"\n") + if not self.WaterHeight is None: + lines.append("w "+str(self.WaterHeight)+"\n") + if self.UsingCaelum: + lines.append("caelum\n") + lines.append(self.SkyColorLine.strip()+"\n") + + ar = [] + ar.append(str(self.TruckStartPosition[0])) + ar.append(str(self.TruckStartPosition[1])) + ar.append(str(self.TruckStartPosition[2])) + ar.append(str(self.CameraStartPosition[0])) + ar.append(str(self.CameraStartPosition[1])) + ar.append(str(self.CameraStartPosition[2])) + if not self.CharacterStartPosition is None: + ar.append(str(self.CharacterStartPosition[0])) + ar.append(str(self.CharacterStartPosition[1])) + ar.append(str(self.CharacterStartPosition[2])) + startline = ", ".join(ar)+"\n" + lines.append(startline) + + + #save trucks + for truck in self.trucks: + trucklines = self.getObjectLines(truck) + for l in trucklines: + lines.append(l) + # save loads + for load in self.loads: + loadlines = self.getObjectLines(load) + for l in loadlines: + lines.append(l) + + # save objects + for object in self.objects: + objectlines = self.getObjectLines(object) + for l in objectlines: + lines.append(l) + + lines.append("end\n") + self.saveFile(filename, lines) + return True + + \ No newline at end of file Modified: trunk/lib/rorterraineditor/HelpFrame.py =================================================================== --- trunk/lib/rorterraineditor/HelpFrame.py 2007-07-16 13:18:30 UTC (rev 108) +++ trunk/lib/rorterraineditor/HelpFrame.py 2007-07-20 00:31:37 UTC (rev 109) @@ -8,7 +8,7 @@ self.btnExit = wx.Button(self, wx.ID_ANY, "OK") self.Bind(wx.EVT_BUTTON, self.onExit , self.btnExit) self.__do_layout() - self.filename = "readme.txt" + self.filename = "terrainreadme.txt" self.LoadHelp() def LoadHelp(self): Modified: trunk/lib/rorterraineditor/MainFrame.py =================================================================== --- trunk/lib/rorterraineditor/MainFrame.py 2007-07-16 13:18:30 UTC (rev 108) +++ trunk/lib/rorterraineditor/MainFrame.py 2007-07-20 00:31:37 UTC (rev 109) @@ -137,7 +137,7 @@ self.mnuterraincollision = view_menu.AppendCheckItem(ID_TERRAINCOLLISION, "Camera collides with Terrain", "") self.mnuterraincollision.Check(True) view_menu.AppendSeparator() - self.viewObjectDetails = view_menu.AppendCheckItem(ID_VIEWOBJ, "&View Objects", "Display object details") + self.viewObjectDetails = view_menu.AppendCheckItem(ID_VIEWOBJ, "&Additional Object View Window", "creates two additional views") self.viewObjectDetails.Check(False) view_menu.AppendSeparator() view_menu.Append(ID_OGRESET, "&Ogre Settings", "Change Ogre Display Settings") @@ -186,11 +186,10 @@ default = "" if self.rordir: default = os.path.join(self.rordir, TRUCKDIR) - print default dialog = wx.FileDialog(self, "Add Truck", default, "", "Truck and Load Files (*.truck,*.load)|*.truck;*.load", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) res = dialog.ShowModal() if res == wx.ID_OK: - if not self.terrainOgreWin.addTruckToTerrain(dialog.GetPath()): + if not self.terrainOgreWin.addTruckToTerrain(truckFilename=dialog.GetPath()): dlg = wx.MessageDialog(self, "You must select a position on the ground first!", "error", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() @@ -199,12 +198,10 @@ default = "" if self.rordir: default = os.path.join(self.rordir, OBJECTDIR) - print default dialog = wx.FileDialog(self, "Add Object", default, "", "RoR Object Definitions (*.odef)|*.odef", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) res = dialog.ShowModal() if res == wx.ID_OK: - print dialog.GetPath() - if not self.terrainOgreWin.addMeshToTerrain(dialog.GetPath()): + if not self.terrainOgreWin.addObjectToTerrain(odefFilename=dialog.GetPath()): dlg = wx.MessageDialog(self, "You must select a position on the ground first!", "error", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() @@ -217,15 +214,15 @@ self.terrainOgreWin.stickCurrentObjectToGround = self.btnStickToGround.GetValue() def updateObjPosRot(self, event=None): - if self.terrainOgreWin.mSelected is None: + if self.terrainOgreWin.selectedEntry is None: self.statusbar.SetStatusText("", 1) return - n = self.terrainOgreWin.mSelected.getParentNode() - comment = self.terrainOgreWin.getCommentsForObject(n.getName()).lstrip('/') - if comment.strip() != "": - txt = "%s / %s" % (n.getName(), comment) - else: - txt = "%s" % n.getName() + entry = self.terrainOgreWin.selectedEntry + #comment = self.terrainOgreWin.getCommentsForObject(n.getName()).lstrip('/') + #if comment.strip() != "": + # txt = "%s / %s" % (n.getName(), comment) + #else: + txt = "%s %s" % (entry.data.name, " ".join(entry.data.additionaloptions)) self.statusbar.SetStatusText(txt, 1) posx, posy, posz, rotx, roty, rotz = self.terrainOgreWin.getSelectionPositionRotation() @@ -248,8 +245,8 @@ self.terrainOgreWin.TerrainName = self.terrainNamectrl.GetValue() def OnChangeWaterLevel(self, event=None): - self.terrainOgreWin.WaterHeight = self.waterlevelctrl.GetValue() - self.waterLevelText.Label = "Water Level: %0.1f" % (self.terrainOgreWin.WaterHeight) + self.terrainOgreWin.terrain.WaterHeight = self.waterlevelctrl.GetValue() + self.waterLevelText.Label = "Water Level: %0.1f" % (self.terrainOgreWin.terrain.WaterHeight) self.terrainOgreWin.updateWaterPlane() def OnChangeOgreSettings(self, event): @@ -259,7 +256,7 @@ dlg.Destroy() def OnFileSave(self, event): - if self.terrainOgreWin.SaveTerrnFile(): + if self.terrainOgreWin.SaveTerrain(): dlg = wx.MessageDialog(self, "saved","info", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() @@ -275,7 +272,7 @@ dialog = wx.FileDialog(self, "Save Terrain as", default, "", "Terrain Files (*.terrn)|*.terrn", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) res = dialog.ShowModal() if res == wx.ID_OK: - if self.terrainOgreWin.SaveTerrnFile(dialog.GetPath()): + if self.terrainOgreWin.SaveTerrain(dialog.GetPath()): dlg = wx.MessageDialog(self, "saved","info", wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() @@ -310,9 +307,9 @@ self.terrainOgreWin.LoadTerrain(filename) #update some controls if finished loading - self.waterlevelctrl.SetValue(self.terrainOgreWin.WaterHeight) - self.waterLevelText.Label = "Water Level: %0.1f" % (self.terrainOgreWin.WaterHeight) - self.terrainNamectrl.SetValue(self.terrainOgreWin.TerrainName) + self.waterlevelctrl.SetValue(self.terrainOgreWin.terrain.WaterHeight) + self.waterLevelText.Label = "Water Level: %0.1f" % (self.terrainOgreWin.terrain.WaterHeight) + self.terrainNamectrl.SetValue(self.terrainOgreWin.terrain.TerrainName) def onViewObjectDetails(self, event=None): Modified: trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py =================================================================== --- trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py 2007-07-16 13:18:30 UTC (rev 108) +++ trunk/lib/rorterraineditor/RoRTerrainOgreWindow.py 2007-07-20 00:31:37 UTC (rev 109) @@ -2,44 +2,59 @@ import wx, os, os.path import ogre.renderer.OGRE as ogre from ror.truckparser import * +from ror.terrainparser import * from wxogre.OgreManager import * from wxogre.wxOgreWindow import * -from random import random +from ror.rorcommon import * ADDEDBY = "//added by the terrrain editor:\n" -SHIFT_SPEED_FACTOR = 15 +SHIFT_SPEED_FACTOR = 20 SLOW_DOWN_FACTOR = 0.75 LOW_SPEED_THRESHOLD = 1 +# this class holds all the needed 3d data and also the underlying object data +class Entry: + node = None + entity = None + data = None + + class RoRTerrainOgreWindow(wxOgreWindow): + terrain = None + clearlist = {'entity':[]} + + selectedEntry = None + selectedCoords = None + + cameralandcollisionenabled = True + + entries = {} - #myObjects = {} - myODefs = {} + # movement related + keyPress = ogre.Vector3(0,0,0) + moveVector = ogre.Vector3(0,0,0) + # selection related + selectionMaterial = None + selectionMaterialAnimState = 0 + + + SelectedArrow = None + StartDragLeftX = (0,0) + StartDragLeftY = (0,0) + TranslationRotationMode = False + TranslateNode = None + RotateNode = None + stickCurrentObjectToGround = False + def __init__(self, parent, ID, size = wx.Size(200,200), rordir = "", **kwargs): self.rordir = rordir - self.rand = str(random()) - self.TerrainLoaded = False - self.mCount = 0 - self.rand = str(random()) + self.parent = parent self.size = size self.kwargs = kwargs self.ID = ID - self.mSelected = None - self.selectedCoords = None - self.meshesorder = [] - self.additionaloptions = {} - self.trucksorder = [] - self.myODefs = {} - self.trucks = {} - self.comments = {} - self.cameralandcollisionenabled = True - self.meshes = {} - self.keyPress = ogre.Vector3(0,0,0) - self.moveVector = ogre.Vector3(0,0,0) - self.selectionMaterial = None - self.selectionMaterialAnimState = 0 + wxOgreWindow.__init__(self, self.parent, self.ID, size = self.size, **self.kwargs) def CameraLandCollision(self, value): @@ -48,9 +63,9 @@ def animateSelection(self): if not self.selectionMaterial is None: self.selectionMaterialAnimState += 0.01 - if self.selectionMaterialAnimState >= 0.4: - self.selectionMaterialAnimState = - 0.4 - val = 0.6 + abs(self.selectionMaterialAnimState) + if self.selectionMaterialAnimState >= 0.2: + self.selectionMaterialAnimState = - 0.2 + val = 0.8 + abs(self.selectionMaterialAnimState) #print val self.selectionMaterial.setDiffuse(1, 0.3, 0, val) self.selectionMaterial.setSpecular(1, 0.3, 0, val) @@ -60,7 +75,10 @@ self.cameraLandCollision() self.animateSelection() if not self.TranslateNode is None: - if self.mSelected: + if self.selectedEntry: + if not self.selectedEntry.data.mayRotate and self.TranslationRotationMode: + self.TranslationRotationMode = False + if self.TranslationRotationMode: # rotation mode self.TranslateNode.setScale(0,0,0) @@ -127,7 +145,8 @@ self.sceneManager = getOgreManager().createSceneManager(ogre.ST_EXTERIOR_CLOSE) # create a camera - self.camera = self.sceneManager.createCamera('Camera' + self.rand) + cameraUUID = randomID() + self.camera = self.sceneManager.createCamera(str(cameraUUID)+"camera") self.camera.lookAt(ogre.Vector3(0, 0, 0)) self.camera.setPosition(ogre.Vector3(0, 0, 100)) self.camera.nearClipDistance = 0.1 @@ -149,199 +168,34 @@ #create objects self.populateScene() - def loadOdef(self, objname): - try: - f=open(self.rordir+"\\data\\objects\\%s.odef" % (objname), 'r') - content = f.readlines() - f.close() - meshname = content[0].strip() - scalearr = content[1].split(",") - self.myODefs[objname] = [] - if len(content) > 2: - for i in range(1,len(content)): - line = content[i] - if line.lower().strip() == "end": - break - self.myODefs[objname].append(line.split(",")) - return (meshname, float(scalearr[0]), float(scalearr[1]), float(scalearr[2])) - else: - return (meshname, 1, 1, 1) - except Exception, err: - print "error while processing odef file of %s" % objname - print str(err) - + def updateWaterPlane(self): - self.planenode.setPosition(1500, self.WaterHeight + 200, 1500) + self.waternode.setPosition(1500, self.terrain.WaterHeight + 200, 1500) def createWaterPlane(self): - if self.WaterHeight is None: + if self.terrain.WaterHeight is None: return plane = ogre.Plane() plane.normal = ogre.Vector3(0, 1, 0) plane.d = 200 # see http://www.ogre3d.org/docs/api/html/classOgre_1_1MeshManager.html#Ogre_1_1MeshManagera5 - mesh = ogre.MeshManager.getSingleton().createPlane('WaterPlane' + self.rand, "General", plane, 3000, 3000, + waterid = str(randomID()) + mesh = ogre.MeshManager.getSingleton().createPlane(waterid+'WaterPlane', "General", plane, 3000, 3000, 20, 20, True, 1, 50.0, 50.0, ogre.Vector3(0, 0, 1), ogre.HardwareBuffer.HBU_STATIC_WRITE_ONLY, ogre.HardwareBuffer.HBU_STATIC_WRITE_ONLY, True, True) - entity = self.sceneManager.createEntity('waterent', 'WaterPlane' + self.rand) - entity.setMaterialName('mysimple/water') - self.planenode = self.sceneManager.getRootSceneNode().createChildSceneNode() - self.planenode.attachObject(entity) + self.waterentity = self.sceneManager.createEntity(waterid+"entity", waterid+'WaterPlane') + self.waterentity.setMaterialName('mysimple/water') + + self.waternode = self.sceneManager.getRootSceneNode().createChildSceneNode() + self.waternode.attachObject(self.waterentity) self.updateWaterPlane() - - def processTerrnFile(self, content): - #self.parent.cbObjects.Clear() - linecounter = 0 - self.UsingCaelum = False - self.WaterHeight = None - comm = [] - for i in range(0, len(content)): - if content[i].strip() == "": - comm.append(content[i]) - continue - if content[i].strip()[0:2] == "//": - comm.append(content[i]) - continue - if content[i].strip()[0:1] == ";": - comm.append(content[i].replace(";","//")) - continue - if content[i].strip().lower() == "end": - continue - linecounter += 1 - if linecounter == 1: - #terrain name - self.TerrainName = content[i].strip() - continue - elif linecounter == 2: - # .cfg file - self.TerrainConfig = content[i].strip() - continue - if content[i].strip()[0].lower() == "w": - self.WaterHeight = float(content[i].strip()[2:]) - continue - if content[i].strip().lower() == "caelum": - self.UsingCaelum = True - continue - if linecounter < 10 and len(content[i].split(",")) == 3: - # sky color - sc = content[i].split(",") - self.SkyColor = (float(sc[0]), float(sc[1]), float(sc[2])) - self.SkyColorLine = content[i] - continue - if linecounter < 10 and len(content[i].split(",")) == 9 or len(content[i].split(",")) == 6: - # spawning Position - sp = content[i].split(",") - self.TruckStartPosition = ogre.Vector3(float(sp[0]), float(sp[1]), float(sp[2])) - - #insert truckshop - # n = self.sceneManager.getRootSceneNode().createChildSceneNode("objectts") - # e = self.sceneManager.createEntity("objentts", "truckshop.mesh") - # n.attachObject(e) - # n.setPosition(self.TruckStartPosition) - # n.rotate(ogre.Vector3.UNIT_X, ogre.Degree(-90).valueRadians()) - # self.myObjects["objectts"] = n - - self.CameraStartPosition = ogre.Vector3(float(sp[3]), float(sp[4]), float(sp[5])) - if len(sp) == 9: - self.CharacterStartPosition = ogre.Vector3(float(sp[6]), float(sp[7]), float(sp[8])) - else: - self.CharacterStartPosition = None - continue - arr = content[i].split(",") - #try: - x = float(arr[0]) - y = float(arr[1]) - z = float(arr[2]) - rx = float(arr[3]) - ry = float(arr[4]) - rz = float(arr[5]) - objname = (arr[6]).strip().split("\t") - if len(objname) == 1: - objname = (arr[6]).strip().split(" ") - #print objname - if objname[0][0:5] == "truck" and len(objname) > 1: - print "loading truck..." - fn = self.rordir + "\\data\\trucks\\"+objname[-1].strip() - n, entname = self.createTruckMesh(fn) - if not n is None: - self.comments[entname] = comm - comm = [] - n.rotate(ogre.Vector3.UNIT_X, ogre.Degree(rx).valueRadians(), relativeTo=ogre.Node.TransformSpace.TS_WORLD) - n.rotate(ogre.Vector3.UNIT_Y, ogre.Degree(ry).valueRadians(), relativeTo=ogre.Node.TransformSpace.TS_WORLD) - n.rotate(ogre.Vector3.UNIT_Z, ogre.Degree(-rz).valueRadians(), relativeTo=ogre.Node.TransformSpace.TS_WORLD) - n.setPosition(x, y, z) - continue - if objname[0][0:4] == "load" and len(objname) > 1: - print "loading load...." - fn = self.rordir + "\\data\\trucks\\"+objname[-1].strip() - n, entname = self.createTruckMesh(fn) - if not n is None: - self.comments[entname] = comm - comm = [] - n.rotate(ogre.Vector3.UNIT_X, ogre.Degree(rx).valueRadians(), relativeTo=ogre.Node.TransformSpace.TS_WORLD) - n.rotate(ogre.Vector3.UNIT_Y, ogre.Degree(ry).valueRadians(), relativeTo=ogre.Node.TransformSpace.TS_WORLD) - n.rotate(ogre.Vector3.UNIT_Z, ogre.Degree(-rz).valueRadians(), relativeTo=ogre.Node.TransformSpace.TS_WORLD) - n.setPosition(x, y, z) - continue - firstobjname = objname[0] - - try: - (meshname, sx, sy, sz) = self.loadOdef(firstobjname) - except Exception, inst: - print inst - print "########## error loading odef of %s" % firstobjname - sx = None - - n = self.sceneManager.getRootSceneNode().createChildSceneNode("object" + str(i)+ firstobjname) - entname = "objent" + str(i)+"_"+firstobjname - e = self.sceneManager.createEntity(entname, meshname) - n.attachObject(e) - - #print "position: ", x,", ", y,", ", z - #print "rotation: ", rx,", ", ry,", ", rz - #print "scale: ", sx,", ", sy,", ", sz - n.setPosition(x, y, z) - n.rotate(ogre.Vector3.UNIT_X, ogre.Degree(-90),relativeTo=ogre.Node.TransformSpace.TS_WORLD) - n.rotate(ogre.Vector3.UNIT_Z, ogre.Degree(rz),relativeTo=ogre.Node.TransformSpace.TS_PARENT) - n.rotate(ogre.Vector3.UNIT_Y, ogre.Degree(ry),relativeTo=ogre.Node.TransformSpace.TS_PARENT) - n.rotate(ogre.Vector3.UNIT_X, ogre.Degree(rx),relativeTo=ogre.Node.TransformSpace.TS_PARENT) - if not sx is None: - n.setScale(sx, sy, sz) - self.comments[entname] = comm - comm = [] - self.meshesorder.append(entname) - if len(objname) > 1: - self.additionaloptions[entname] = objname[1:] - self.meshes[entname] = n - - #except Exception, inst: - # print inst - # print "error parsing line %s" % content[i] - self.createWaterPlane() - self.createArrows() - if not self.CharacterStartPosition is None: - self.camera.setPosition(self.CharacterStartPosition) - else: - self.camera.setPosition(self.CameraStartPosition) - - def formatFloat(self, fl): - return "%12s" % ("%0.6f" % (float(fl))) - - - def getCommentsForObject(self, entname): - if entname in self.comments.keys(): - #print self.comments[entname] - return self.comments[entname]; - else: - return "" - def getSelectionPositionRotation(self): - if not self.mSelected is None: - return self.getPositionRotation(self.mSelected.getParentNode()) + if not self.selectedEntry is None: + return self.getPositionRotation(self.selectedEntry.node) def getPositionRotation(self, obj): scale = obj.getScale() @@ -358,92 +212,6 @@ rotz = -ogre.Radian(rot.getYaw(False)).valueDegrees() return pos.x, pos.y, pos.z, rotx, roty, rotz - def SaveTerrnFile(self, fn = None): - if fn is None: - fn = self.terrnfile - # quick and dirty ;) - #try: - lines = [] - lines.append(self.TerrainName+"\n") - lines.append(self.TerrainConfig+"\n") - if not self.WaterHeight is None: - lines.append("w "+str(self.WaterHeight)+"\n") - if self.UsingCaelum: - lines.append("caelum\n") - lines.append(self.SkyColorLine.strip()+"\n") - - ar = [] - ar.append(str(self.TruckStartPosition.x)) - ar.append(str(self.TruckStartPosition.y)) - ar.append(str(self.TruckStartPosition.z)) - ar.append(str(self.CameraStartPosition.x)) - ar.append(str(self.CameraStartPosition.y)) - ar.append(str(self.CameraStartPosition.z)) - if not self.CharacterStartPosition is None: - ar.append(str(self.CharacterStartPosition.x)) - ar.append(str(self.CharacterStartPosition.y)) - ar.append(str(self.CharacterStartPosition.z)) - startline = ", ".join(ar)+"\n" - lines.append(startline) - - - #save trucks and loads: - - for k in self.trucksorder: - - if k in self.comments.keys(): - for c in self.comments[k]: - lines.append(c) - - posx, posy, posz, rotx, roty, rotz = self.getPositionRotation(self.trucks[k]) - - rotx -= 90 - - truckstring = k.split(".")[-1] + "\t " + k - ar = [self.formatFloat(posx), - self.formatFloat(posy), - self.formatFloat(posz), - self.formatFloat(rotx), - self.formatFloat(roty), - self.formatFloat(rotz), - truckstring] - line = ", ".join(ar) - lines.append(line.strip()+"\n") - - # save meshs - for k in self.meshesorder: - - if k in self.comments.keys(): - for c in self.comments[k]: - lines.append(c) - - posx, posy, posz, rotx, roty, rotz = self.getPositionRotation(self.meshes[k]) - meshstring = k.split("_")[-1] - ar = [self.formatFloat(posx), - self.formatFloat(posy), - self.formatFloat(posz), - self.formatFloat(rotx), - self.formatFloat(roty), - self.formatFloat(rotz), - meshstring] - line = ", ".join(ar) - - if k in self.additionaloptions.keys(): - for ao in self.additionaloptions[k]: - line += " " + ao.strip() - - lines.append(line.strip()+"\n") - - lines.append("end\n") - - f=open(fn, 'w') - f.writelines(lines) - f.close() - return True - #except: - # return False - - def reattachArrows(self, entity): self.TranslateNode.setPosition(entity.getParentNode().getPosition()) self.TranslateNode.setOrientation(entity.getParentNode().getOrientation()) @@ -502,48 +270,282 @@ self.TerrainSelectNode = nt self.TranslateNode = n self.RotateNode = nr - n.setPosition(self.CameraStartPosition) - nr.setPosition(self.CameraStartPosition) + n.setPosition(0,0,0) + nr.setPosition(0,0,0) def deselectSelection(self): - if self.mSelected: - #self.mSelected.getSubEntity(0).setMaterialName(self.oldmaterial) - self.mSelected.setMaterialName(self.oldmaterial) - self.mSelected.getParentSceneNode().showBoundingBox(False) + if self.selectedEntry: + #self.selectedEntry.entity.getSubEntity(0).setMaterialName(self.oldmaterial) + self.selectedEntry.entity.setMaterialName(self.oldmaterial) + self.selectedEntry.entity.getParentSceneNode().showBoundingBox(False) def changeSelection(self, newnode): self.deselectSelection() - self.mSelected = newnode - self.oldmaterial = self.mSelected.getSubEntity(0).getMaterialName() + key = newnode.getName()[:-len("entity")] + self.selectedEntry = self.entries[key] + self.oldmaterial = self.selectedEntry.entity.getSubEntity(0).getMaterialName() + newmatname = "mysimple/selectedobject" selectedmat = ogre.MaterialManager.getSingleton().getByName(newmatname) - mat = ogre.MaterialManager.getSingleton().getByName(self.mSelected.getSubEntity(0).getMaterialName()) + mat = ogre.MaterialManager.getSingleton().getByName(self.selectedEntry.entity.getSubEntity(0).getMaterialName()) if not mat is None: mat.copyDetailsTo(selectedmat) newmat = ogre.MaterialManager.getSingleton().getByName(newmatname) newmat.setSceneBlending(ogre.SceneBlendFactor.SBF_SOURCE_ALPHA, ogre.SceneBlendFactor.SBF_DEST_ALPHA ) newmat.setSelfIllumination(1, 0.3, 0) - newmat.setDiffuse(1, 0.3, 0, 0.5) + newmat.setDiffuse(1, 0.3, 0, 0.9) newmat.setAmbient(1, 0.3, 0) - newmat.setSpecular(1, 0.3, 0, 0.5) + newmat.setSpecular(1, 0.3, 0, 0.9) self.selectionMaterial = newmat - #self.mSelected.getSubEntity(0).setMaterialName(snewmatname) - self.mSelected.setMaterialName(newmatname) - self.mSelected.getParentSceneNode().showBoundingBox(True) - self.reattachArrows(self.mSelected) - self.arrowScale = self.mSelected.getBoundingRadius() / 100 + #self.selectedEntry.entity.getSubEntity(0).setMaterialName(snewmatname) + self.selectedEntry.entity.setMaterialName(newmatname) + self.selectedEntry.entity.getParentSceneNode().showBoundingBox(True) + self.reattachArrows(self.selectedEntry.entity) + self.arrowScale = self.selectedEntry.entity.getBoundingRadius() / 100 + def free(self): + self.sceneManager.clearScene() + + def updateDataStructures(self): + for uuid in self.entries.keys(): + entry = self.entries[uuid] + x, y, z, rotx, roty, rotz = self.getPositionRotation(entry.node) + if entry.data.name.lower() in ['truck', 'load']: + rotx -= 90 + entry.data.setPosition(x, y, z) + entry.data.setRotation(rotx, roty, rotz) + + def SaveTerrain(self, fn = None): + self.updateDataStructures() + if not self.terrain is None: + return self.terrain.save(fn) + + def LoadTerrain(self, filename): + + if not self.terrain is None: + self.free() + self.terrain = RoRTerrain(filename) - def LoadTerrnFile(self, filename): - self.terrnfile = filename - f=open(filename, 'r') + cfgfile = os.path.join(os.path.dirname(filename), self.terrain.TerrainConfig) + self.sceneManager.setWorldGeometry(cfgfile) + + self.createWaterPlane() + self.createArrows() + if not self.terrain.CharacterStartPosition is None: + self.camera.setPosition(self.terrain.CharacterStartPosition) + else: + self.camera.setPosition(self.terrain.CameraStartPosition) + + for truck in self.terrain.trucks: + self.addTruckToTerrain(data=truck) + + for load in self.terrain.loads: + self.addTruckToTerrain(data=load) + + for object in self.terrain.objects: + self.addObjectToTerrain(data=object) + + + + def loadOdef(self, odefFilename): + f=open(odefFilename, 'r') content = f.readlines() f.close() - self.processTerrnFile(content) + meshname = content[0].strip() + scalearr = [1,1,1] + if len(content) > 2: + scalearr = content[1].split(",") + + return (meshname, float(scalearr[0]), float(scalearr[1]), float(scalearr[2])) + + + + def addObjectToTerrain(self, data=None, odefFilename=None, coords=None): + if coords is None: + coords = self.selectedCoords + if coords is None and data is None: + return False + + uuid = randomID() + + if data is None: + data = Object() + data.name = os.path.basename(odefFilename).split(".")[0] + data.filename = os.path.basename(odefFilename).split(".")[0] + data.comments = ['// added by terrain editor\n'] + data.setPosition(coords.x, coords.y, coords.z) + data.setRotation(0, 0, 0) + data.additionaloptions =[] + self.terrain.objects.append(data) + else: + odefFilename = data.filename + + if os.path.basename(odefFilename) == odefFilename: + if odefFilename[-5:] != ".odef": + odefFilename += ".odef" + odefFilename = self.rordir + "\\data\\objects\\"+odefFilename + meshname = None + try: + (meshname, sx, sy, sz) = self.loadOdef(odefFilename) + except Exception, err: + data.error=True + log().error("error while processing odef file %s" % odefFilename) + log().error(str(err)) + return + + entry = Entry() + entry.node = self.sceneManager.getRootSceneNode().createChildSceneNode(str(uuid)+"node") + entry.entity = self.sceneManager.createEntity(str(uuid)+"entity", meshname) + entry.data = data + + entry.node.attachObject(entry.entity) + entry.node.rotate(ogre.Vector3.UNIT_X, ogre.Degree(-90),relativeTo=ogre.Node.TransformSpace.TS_WORLD) + entry.node.rotate(ogre.Vector3.UNIT_Z, ogre.Degree(data.rotz).valueRadians(), relativeTo=ogre.Node.TransformSpace.TS_WORLD) + entry.node.rotate(ogre.Vector3.UNIT_Y, ogre.Degree(data.roty).valueRadians(), relativeTo=ogre.Node.TransformSpace.TS_WORLD) + entry.node.rotate(ogre.Vector3.UNIT_X, ogre.Degree(data.rotx).valueRadians(), relativeTo=ogre.Node.TransformSpace.TS_WORLD) + entry.node.setPosition(data.x, data.y, data.z) + if not sx is None: + entry.node.setScale(sx, sy, sz) + + self.entries[uuid] = entry + return True + + def addTruckToTerrain(self, data=None, truckFilename=None, coords=None): + if coords is None: + coords = self.selectedCoords + if coords is None and data is None: + return False + + uuid = randomID() + + if data is None: + data = Object() + data.name = truckFilename.split(".")[-1] # truck or load + data.filename = os.path.basename(truckFilename) + data.comments = ['// added by terrain editor\n'] + data.setPosition(coords.x, coords.y, coords.z) + data.setRotation(0, 0, 0) + data.additionaloptions =[data.filename] + if truckFilename.split(".")[-1].lower() == "truck": + self.terrain.trucks.append(data) + elif truckFilename.split(".")[-1].lower() == "load": + self.terrain.loads.append(data) + else: + truckFilename = data.filename + + if os.path.basename(truckFilename) == truckFilename: + truckFilename = self.rordir + "\\data\\trucks\\"+truckFilename + + entry = Entry() + entry.node, entry.entity, entry.manualobject = self.createTruckMesh(truckFilename, uuid) + entry.data = data + + entry.node.rotate(ogre.Vector3.UNIT_Z, ogre.Degree(data.rotz).valueRadians(), relativeTo=ogre.Node.TransformSpace.TS_WORLD) + entry.node.rotate(ogre.Vector3.UNIT_Y, ogre.Degree(data.roty).valueRadians(), relativeTo=ogre.Node.TransformSpace.TS_WORLD) + entry.node.rotate(ogre.Vector3.UNIT_X, ogre.Degree(data.rotx).valueRadians(), relativeTo=ogre.Node.TransformSpace.TS_WORLD) + entry.node.setPosition(data.x, data.y, data.z) + self.entries[uuid] = entry + return True + + def createTruckMesh(self, fn, uuid): + if not os.path.isfile(fn): + #print "truck file not found: " + fn + return + p = rorparser() + p.parse(fn) + if not 'nodes' in p.tree.keys() or not 'beams' in p.tree.keys() : + return False + + try: + myManualObject = self.sceneManager.createManualObject(str(uuid)+"manual") + + #myManualObjectMaterial = ogre.MaterialManager.getSingleton().create("manualmaterial"+truckname+str(self.randomcounter),"debugger"); + #myManualObjectMaterial.setReceiveShadows(False) + #myManualObjectMaterial.getTechnique(0).setLightingEnabled(True) + #myManualObjectMaterial.getTechnique(0).getPass(0).setDiffuse(0,0,1,0) + #myManualObjectMaterial.getTechnique(0).getPass(0).setAmbient(0,0,1) + #myManualObjectMaterial.getTechnique(0).getPass(0).setSelfIllumination(0,0,1) + #myManualObjectMaterial.getTechnique(0).getPass(0).setCullingMode(ogre.CULL_ANTICLOCKWISE) + + matname = "" + if fn[-4:].lower() == "load": + matname = 'mysimple/loadcolor' + elif fn[-5:].lower() == "truck": + matname = 'mysimple/truckcolor' + + myManualObject.useIndexes = True + myManualObject.estimateVertexCount(2000) + myManualObject.estimateIndexCount(2000) + + myManualObject.begin(matname+"grid", ogre.RenderOperation.OT_LINE_LIST) + for nodeobj in p.tree['nodes']: + if nodeobj.has_key('type'): + continue + node = nodeobj['data'] + myManualObject.position(float(node[1]),float(node[2]),float(node[3])) + for beamobj in p.tree['beams']: + if beamobj.has_key('type'): + continue + beam = beamobj['data'] + myManualObject.index(int(beam[0])) + myManualObject.index(int(beam[1])) + myManualObject.end() + myManualObject.begin(matname, ogre.RenderOperation.OT_TRIANGLE_LIST) + for nodeobj in p.tree['nodes']: + if nodeobj.has_key('type'): + continue + node = nodeobj['data'] + myManualObject.position(float(node[1]),float(node[2]),float(node[3])) + + #print len(p.tree['submeshgroups']) + if len(p.tree['submeshgroups']) > 0: + faces = [] + for smobj in p.tree['submeshgroups']: + for cabobj in smobj['cab']: + if cabobj.has_key('type'): + continue + cab = cabobj['data'] + #print "########face" + if cab != []: + try: + myManualObject.triangle(int(cab[0]),int(cab[1]),int(cab[2])) + except: + print "error with cab: " + str(cab) + pass + else: + print "truck has no faces!" + + myManualObject.end() + mesh = myManualObject.convertToMesh(str(uuid)+"manual") + entity = self.sceneManager.createEntity(str(uuid)+"entity", str(uuid)+"manual") + #trucknode = self.sceneManager.getRootSceneNode().createChildSceneNode() + myManualObjectNode = self.sceneManager.getRootSceneNode().createChildSceneNode(str(uuid)+"node") + myManualObjectNode.attachObject(entity) + + myManualObjectNode.attachObject(myManualObject) + + return myManualObjectNode, entity, mesh + except Exception, err: + log().error("error while processing truck file %s" % fn) + log().error(str(err)) + return None, None, None + + def getPointedPosition(self, event): + x, y = event.GetPosition() + width, height, a, b, c = self.renderWindow.getMetrics() + mouseRay = self.camera.getCameraToViewportRay((x / float(width)), (y / float(height))); + myRaySceneQuery = self.sceneManager.createRayQuery(ogre.Ray()); + myRaySceneQuery.setRay(mouseRay) + result = myRaySceneQuery.execute() + if len(result) > 0 and not result[0] is None and not result[0].worldFragment is None: + return result[0].worldFragment.singleIntersection + return None + + def populateScene(self): self.sceneManager.AmbientLight = ogre.ColourValue(0.7, 0.7, 0.7 ) @@ -553,73 +555,16 @@ l = self.sceneManager.createLight("MainLight") l.setPosition(20,80,50) - - - #create the camera Axes object - self.camAxesNode = None - self.camAxesEnt = None #create ray template self.selectionRaySceneQuery = self.sceneManager.createRayQuery(ogre.Ray()); self.terrainRaySceneQuery = self.sceneManager.createRayQuery(ogre.Ray()); + # setup the sky plane plane = ogre.Plane() - # 5000 world units from the camera plane.d = 5000 - # Above the camera, facing down plane.normal = -ogre.Vector3.UNIT_Y - self.SelectedArrow = None - self.StartDragLeftX, self.StartDragLeftY = (0,0) - self.TranslationRotationMode = False - self.TranslateNode = None - self.RotateNode = None - self.stickCurrentObjectToGround = False - self.randomcounter = 0 - - def FixTerrainConfig(self,filename): - print "fixing file %s ..." % filename - f=open(filename, 'r') - content = f.readlines() - f.close() - for i in range(0, len(content)): - if content[i].lower().find("maxpixelerror") >= 0: - content[i] = "MaxPixelError=0\n" - print "FIXED!" - break - f=open(filename, 'w') - f.writelines(content) - f.close() - - - def free(self): - self.sceneManager.clearScene() - # self.sceneManager.destroyAllEntities() - # self.sceneManager.destroyAllManualObjects() - # self.sceneManager.destroyAllAnimations() - # self.sceneManager.destroyAllLights() - - # if self.selectionRaySceneQuery: - # self.sceneManager.destroyQuery(self.selectionRaySceneQuery) - # self.sceneManager.destroyQuery(self.terrainRaySceneQuery) - # if self.renderWindow: - # self.renderWindow.removeAllViewports() - #ogre.ResourceGroupManager.getSingleton().destroyResourceGroup("General") - #ogre.ResourceGroupManager.getSingleton().destroyResourceGroup("Bootstrap") - - #self.SceneInitialisation() - - def LoadTerrain(self, filename): - # create scene - self.free() - dirname = os.path.dirname(filename) - self.LoadTerrnFile(filename) - cfgname = os.path.join(dirname, self.TerrainConfig) - self.FixTerrainConfig(cfgname) - self.sceneManager.setWorldGeometry(cfgname) - self.TerrainLoaded = True - - def toggleTranslationRotationMode(self): self.TranslationRotationMode = not self.TranslationRotationMode @@ -634,13 +579,12 @@ return nPos def ObjectResetRotation(self): - if self.mSelected: - self.mSelected.getParentNode().resetOrientation() - self.mSelected.getParentNode().rotate(ogre.Vector3.UNIT_X, ogre.Degree(-90),relativeTo=ogre.Node.TransformSpace.TS_WORLD) + if self.selectedEntry: + self.selectedEntry.node.resetOrientation() + self.selectedEntry.node.rotate(ogre.Vector3.UNIT_X, ogre.Degree(-90),relativeTo=ogre.Node.TransformSpace.TS_WORLD) self.RotateNode.resetOrientation() self.RotateNode.rotate(ogre.Vector3.UNIT_X, ogre.Degree(-90),relativeTo=ogre.Node.TransformSpace.TS_WORLD) - def selectarrow(self, arrow): if self.SelectedArrow.getSubEntity(0).getMaterialName()[-3:] != "sel": self.SelectedArrow.setMaterialName(self.SelectedArrow.getSubEntity(0).getMaterialName()+"sel") @@ -651,7 +595,7 @@ def selectTerrain(self, event): self.deselectSelection() - self.mSelected = None + self.selectedEntry = None self.selectedCoords = self.getPointedPosition(event) self.selectedCoords += ogre.Vector3(0,1,0) self.TerrainSelectNode.setPosition(self.selectedCoords) @@ -674,12 +618,16 @@ self.selectarrow(self.SelectedArrow) return selectedSomething = False + ignorearray = [] + ignorearray.append("circlepointer") + if not self.terrain.WaterHeight is None: + ignorearray.append(self.waterentity.getName()) for r in result: if not r is None and not r.movable is None and r.movable.getMovableType() == "Entity": - if r.movable.getName() in ["waterent", "circlepointer"]: + if r.movable.getName() in ignorearray: # you cannot select these objects continue - if not self.mSelected is None and self.mSelected.getName() == r.movable.getName(): + if not self.selectedEntry is None and self.selectedEntry.entity.getName() == r.movable.getName(): continue #print r.movable.getMovableType(), r.movable.getName() if not self.SelectedArrow is None: @@ -722,190 +670,37 @@ if self.stickCurrentObjectToGround: self.TranslateNode.setPosition(self.StickVectorToGround(self.TranslateNode.getPosition())) self.RotateNode.setPosition(self.TranslateNode.getPosition()) - if self.mSelected: - self.mSelected.getParentNode().setPosition(self.TranslateNode.getPosition()) + if self.selectedEntry: + self.selectedEntry.node.setPosition(self.TranslateNode.getPosition()) elif self.SelectedArrow.getName() == 'movearrowsY': self.TranslateNode.translate(0,0,forcex,relativeTo=ogre.Node.TransformSpace.TS_LOCAL) if self.stickCurrentObjectToGround: self.TranslateNode.setPosition(self.StickVectorToGround(self.TranslateNode.getPosition())) self.RotateNode.setPosition(self.TranslateNode.getPosition()) - if self.mSelected: - self.mSelected.getParentNode().setPosition(self.TranslateNode.getPosition()) + if self.selectedEntry: + self.selectedEntry.node.setPosition(self.TranslateNode.getPosition()) elif self.SelectedArrow.getName() == 'movearrowsZ': self.TranslateNode.translate(0,forcex,0,relativeTo=ogre.Node.TransformSpace.TS_LOCAL) if self.stickCurrentObjectToGround: self.TranslateNode.setPosition(self.StickVectorToGround(self.TranslateNode.getPosition())) self.RotateNode.setPosition(self.TranslateNode.getPosition()) - if self.mSelected: - self.mSelected.getParentNode().setPosition(self.TranslateNode.getPosition()) + if self.selectedEntry: + self.selectedEntry.node.setPosition(self.TranslateNode.getPosition()) elif self.SelectedArrow.getName() == 'rotatearrowsX': self.RotateNode.yaw(forceDegree) - if self.mSelected: - self.mSelected.getParentNode().yaw(forceDegre... [truncated message content] |
From: <ror...@us...> - 2007-07-23 13:40:43
|
Revision: 115 http://roreditor.svn.sourceforge.net/roreditor/?rev=115&view=rev Author: rorthomas Date: 2007-07-23 06:40:41 -0700 (Mon, 23 Jul 2007) Log Message: ----------- * improved output Modified Paths: -------------- trunk/installmod.py trunk/lib/ror/depcheckerplugins/ror_cfg.py trunk/lib/ror/truckparser.py Modified: trunk/installmod.py =================================================================== --- trunk/installmod.py 2007-07-23 12:18:36 UTC (rev 114) +++ trunk/installmod.py 2007-07-23 13:40:41 UTC (rev 115) @@ -41,7 +41,7 @@ UnZIP.unzip(filename, TEMPDIR) return True else: - log.info("copying "+filename+" to "+os.path.join(TEMPDIR, os.path.basename(filename))) + log().info("copying "+filename+" to "+os.path.join(TEMPDIR, os.path.basename(filename))) shutil.copyfile(filename, os.path.join(TEMPDIR, os.path.basename(filename))) return False @@ -96,6 +96,10 @@ validtargets = [] invalidtargets = [] + if len(targets) == 0: + log().info("### no targets found") + return validtargets, invalidtargets + log().info("### found %d targets, checking them separatly now" % len(targets)) for target in targets: log().info("### checking target %s..." % target) Modified: trunk/lib/ror/depcheckerplugins/ror_cfg.py =================================================================== --- trunk/lib/ror/depcheckerplugins/ror_cfg.py 2007-07-23 12:18:36 UTC (rev 114) +++ trunk/lib/ror/depcheckerplugins/ror_cfg.py 2007-07-23 13:40:41 UTC (rev 115) @@ -35,6 +35,8 @@ tmp = parseRE(content, re) if not tmp is None: dep.append(tmp) + else: + print "ERROR !!! required value not found in terrain config file %s!" % filename if len(dep) == 0: print "no configuration found in terrain config file " + filename Modified: trunk/lib/ror/truckparser.py =================================================================== --- trunk/lib/ror/truckparser.py 2007-07-23 12:18:36 UTC (rev 114) +++ trunk/lib/ror/truckparser.py 2007-07-23 13:40:41 UTC (rev 115) @@ -535,6 +535,8 @@ return True def errorMsg(self, filename, lineno, sectionname, sectiontype, argname, line, msgold): + if not self.verbose: + return argpath = "/%s/%s/%s" % (sectiontype, sectionname, argname) msg = "%20s:%04d %-30s | %-40s | %s" % \ (os.path.basename(filename), int(lineno) + 1, argpath, @@ -579,6 +581,7 @@ def parse(self, filename, verbose = True): self.filename = filename + self.verbose = verbose content = None try: infile = open(filename,'r') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ror...@us...> - 2007-07-23 15:15:10
|
Revision: 118 http://roreditor.svn.sourceforge.net/roreditor/?rev=118&view=rev Author: rorthomas Date: 2007-07-23 08:15:08 -0700 (Mon, 23 Jul 2007) Log Message: ----------- * renamed installmod to modtool Added Paths: ----------- trunk/modtool.bat trunk/modtool.py Removed Paths: ------------- trunk/installmod.bat trunk/installmod.py Deleted: trunk/installmod.bat =================================================================== --- trunk/installmod.bat 2007-07-23 15:03:49 UTC (rev 117) +++ trunk/installmod.bat 2007-07-23 15:15:08 UTC (rev 118) @@ -1 +0,0 @@ -%systemdrive%\python25\python.exe installmod.py %1 %2 %3 %4 %5 %6 %7 %8 %9 Deleted: trunk/installmod.py =================================================================== --- trunk/installmod.py 2007-07-23 15:03:49 UTC (rev 117) +++ trunk/installmod.py 2007-07-23 15:15:08 UTC (rev 118) @@ -1,317 +0,0 @@ -#Thomas Fischer 31/05/2007, th...@th... -import sys, os, os.path, shutil - -sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) -from ror.logger import log -from ror.settingsManager import getSettingsManager - -TEMPDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "temp") - -def removetemp(reporterrors=True): - if os.path.isdir(TEMPDIR): - try: - shutil.rmtree(TEMPDIR) - #os.rmdir(TEMPDIR) - except Exception, err: - if not reporterrors: - return - log().error(str(err)) - log().error("could not remove temporary diretory: %s! please delete by hand." % TEMPDIR) - sys.exit(1) - -def ExtractToTemp(filename): - file, extension = os.path.splitext(filename) - removetemp(False) - os.mkdir(TEMPDIR) - if extension.lower() == ".rar": - import UnRAR - dst = os.path.join(TEMPDIR, os.path.basename(filename)) - shutil.copyfile(filename, dst) - os.chdir(TEMPDIR) - UnRAR.Archive(os.path.basename(filename)).extract() - - # remove .rar file instantly - os.unlink(os.path.join(TEMPDIR, os.path.basename(filename))) - - # change back to current path - os.chdir(os.path.dirname(os.path.abspath(__file__))) - return True - elif extension.lower() == ".zip": - import UnZIP - UnZIP.unzip(filename, TEMPDIR) - return True - else: - log().info("copying "+filename+" to "+os.path.join(TEMPDIR, os.path.basename(filename))) - shutil.copyfile(filename, os.path.join(TEMPDIR, os.path.basename(filename))) - return False - -def installfile(maintarget, srcfile, dryrun): - file, extension = os.path.splitext(maintarget) - rorpath = getSettingsManager().getSetting("RigsOfRods", "BasePath") - - if extension in ['.truck', '.load']: - path = os.path.join(rorpath, "data", "trucks") - elif extension in ['.terrn']: - path = os.path.join(rorpath, "data", "terrains") - else: - path = rorpath - if dryrun: - log().info("would install %s to %s" % (os.path.basename(srcfile), path)) - else: - log().info("installing %s to %s" % (os.path.basename(srcfile), path)) - shutil.copyfile(srcfile, os.path.join(path, os.path.basename(srcfile))) - -def searchFile(filename, top): - for root, dirs, files in os.walk(top, topdown=False): - if filename in files: - return os.path.join(root, filename) - return None - -def getTargets(verbose): - import ror.depchecker - dc = ror.depchecker.RoRDepChecker(TEMPDIR, "getfiles", "", False) - targets = [] - for file in dc.files: - filename, extension = os.path.splitext(file) - if extension.lower() in ['.truck', '.terrn', '.load']: - targets.append(os.path.basename(file)) - - validtargets = [] - invalidtargets = [] - if len(targets) == 0: - log().info("### no targets found") - return validtargets, invalidtargets - - log().info("### found %d targets, checking them separatly now" % len(targets)) - for target in targets: - log().info("### checking target %s..." % target) - dc = ror.depchecker.RoRDepChecker(TEMPDIR, "dtree", target, verbose) - if dc.everythingfound: - validtargets.append(target) - else: - invalidtargets.append(target) - return validtargets, invalidtargets - -def getRoRMods(verbose): - import ror.depchecker - rorpath = getSettingsManager().getSetting("RigsOfRods", "BasePath") - dc = ror.depchecker.RoRDepChecker(rorpath, "getfiles", "", False) - targets = [] - for file in dc.files: - filename, extension = os.path.splitext(file) - if extension.lower() in ['.truck', '.terrn', '.load']: - targets.append(os.path.basename(file)) - newtargets = [] - md5s = dc.readMD5File() - for target in targets: - if not os.path.basename(target) in md5s.keys(): - newtargets.append(target) - return newtargets - - -def work(mode, targetfile, verbose, dryrun, installtarget=None): - log().info("### modinstaller started with %s, %s" % (mode, targetfile)) - if mode == "install": - filename = os.path.abspath(targetfile) - ExtractToTemp(targetfile) - target = installtarget - log().info("### validating target ...") - import ror.depchecker - dc = ror.depchecker.RoRDepChecker(TEMPDIR, "dtree", target, verbose) - if dc.invalid: - log().error("### target invalid!") - log().info("### please use the list mode to get valid targets") - usage() - - log().info("### target valid!") - #print dc.dstree - installcounter = 0 - for file in dc.dstree: - filename = file['filename'] - filenamefound = searchFile(filename, TEMPDIR) - if filenamefound is None: - log().error("File %s not found in %s!" % (filename, TEMPDIR)) - sys.exit(1) - installfile(target, filenamefound, dryrun) - installcounter += 1 - if dryrun: - log().info("### would install %d files." % installcounter) - else: - log().info("### %d files installed, finished!" % installcounter) - removetemp(False) - return [target] - - elif mode == "installall": - filename = os.path.abspath(targetfile) - ExtractToTemp(targetfile) - validtargets, invalidtargets = getTargets(verbose) - log().info("### installing %d found modifications:" % (len(validtargets))) - installcounter = 0 - for target in validtargets: - log().info("### installing modification '%s'" % target) - import ror.depchecker - dc = ror.depchecker.RoRDepChecker(TEMPDIR, "dtree", target, verbose) - if dc.dstree is None: - log().error("no dependenytree for File %s!" % (filename)) - continue - for file in dc.dstree: - filename = file['filename'] - filenamefound = searchFile(filename, TEMPDIR) - if filenamefound is None: - log().error("File %s not found in %s!" % (filename, TEMPDIR)) - sys.exit(1) - installfile(target, filenamefound, dryrun) - installcounter += 1 - if dryrun: - log().info("### would install %d files." % installcounter) - else: - log().info("### %d files installed, finished!" % installcounter) - removetemp(False) - return validtargets - - elif mode in ["list", "listall"]: - filename = os.path.abspath(targetfile) - ExtractToTemp(targetfile) - validtargets, invalidtargets = getTargets(verbose) - if mode == "listall": - if len(invalidtargets) > 0: - log().info("broken modifications found:") - for v in invalidtargets: - log().info(" %-20s" % v) - log().info("use the --verbose flag to find the missing files!") - else: - log().info("no broken modifications found") - - if len(validtargets) > 0: - log().info("installable modifications found:") - for v in validtargets: - log().info(" %-20s" % v) - else: - log().info("no installable modifications found! :(") - # todo : remove workaround! - removetemp(False) - return validtargets - - elif mode in ["listinstalled"]: - targets = getRoRMods(verbose) - log().info("### Found Mods:") - for target in targets: - log().info(" "+target) - if mode in ["uninstall"]: - rorpath = getSettingsManager().getSetting("RigsOfRods", "BasePath") - log().info("### validating target ...") - import ror.depchecker - dc = ror.depchecker.RoRDepChecker(rorpath, "dtree", targetfile, verbose) - if dc.invalid: - log().error("### target invalid! (Target not found)") - log().info("### please use the 'listinstalled' mode to get valid uninstallation targets") - return None - - log().info("### target valid!") - - #print dc.dstree - newtargets = [] - md5s = dc.readMD5File() - for file in dc.dstree: - filename = file['filename'] - if not os.path.basename(filename) in md5s.keys(): - newtargets.append(filename) - log().info("### removed %d files from dependency tree." % (len(dc.dstree)-len(newtargets))) - #print newtargets - if dryrun: - log().info("### would uninstall %d file(s):" % len(newtargets)) - else: - log().info("### uninstalling %d file(s):" % len(newtargets)) - for target in newtargets: - filenamefound = searchFile(target, rorpath) - if filenamefound is None: - log().error("### File not found: %s" % target) - continue - log().info(" %s" % filenamefound) - if not dryrun: - os.unlink(filenamefound) - - - - return None - -def usage(): - print "usage (general): %s <mode> <additionaloptions> [--verbose] [--dryrun]" % (os.path.basename(sys.argv[0])) - print "list <filename>" - print " list all found and valid modifications in filename" - print "" - print "listall <filename> --verbose" - print " list all found modifications in filename (valid and invalid)" - print "" - print "installall <filename> --verbose --dryrun" - print " install all found modifications in filename" - print "" - print "install <filename> <modification> --verbose --dryrun" - print " install a certain modifications in filename (valid and invalid)" - print "" - print "listinstalled" - print " lists all installed RoR Mods" - print "" - print "uninstall <modname> --verbose --dryrun" - print " uninstalls a mod" - print "" - print "notes: the --verbose option is optional to increase the output for debugging" - print " the --dryrun option is optional and prints out what would be done" - sys.exit(0) - -def main(): - - # check for valid RoR Directory! - import ror.settingsManager - rorpath = ror.settingsManager.getSettingsManager().getSetting("RigsOfRods", "BasePath") - if not os.path.isfile(os.path.join(rorpath,"RoR.exe")): - import ror.starter - ror.starter.startApp() - - if len(sys.argv) < 2: - usage() - - mode = sys.argv[1] - if not mode in ['list', 'listall', 'install', 'installall', 'listinstalled','uninstall']: - usage() - if len(sys.argv) < 4 and mode in ['install']: - usage() - - if mode in ['list', 'listall', 'install', 'installall']: - targetfile = sys.argv[2] - if not os.path.isfile(targetfile): - log().error("%s is not a valid target filename!" % targetfile) - usage() - elif mode in ['listinstalled']: - targetfile = rorpath - elif mode == 'uninstall': - targetfile = sys.argv[2] - - - - # get optional flags - verbose = False - dryrun = False - for option in sys.argv: - if option == "--verbose": - verbose = True - if option == "--dryrun": - dryrun = True - - # Import Psyco if available - try: - import psyco - psyco.full() - except ImportError: - pass - - if len(sys.argv) == 4: - installtarget = sys.argv[3] - else: - installtarget = None - work(mode, targetfile, verbose, dryrun, installtarget) - - - -if __name__=="__main__": - main() \ No newline at end of file Copied: trunk/modtool.bat (from rev 112, trunk/installmod.bat) =================================================================== --- trunk/modtool.bat (rev 0) +++ trunk/modtool.bat 2007-07-23 15:15:08 UTC (rev 118) @@ -0,0 +1 @@ +%systemdrive%\python25\python.exe modtool.py %1 %2 %3 %4 %5 %6 %7 %8 %9 Copied: trunk/modtool.py (from rev 117, trunk/installmod.py) =================================================================== --- trunk/modtool.py (rev 0) +++ trunk/modtool.py 2007-07-23 15:15:08 UTC (rev 118) @@ -0,0 +1,319 @@ +#Thomas Fischer 31/05/2007, th...@th... +import sys, os, os.path, shutil + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) +from ror.logger import log +from ror.settingsManager import getSettingsManager + +TEMPDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "temp") + +def removetemp(reporterrors=True): + if os.path.isdir(TEMPDIR): + try: + shutil.rmtree(TEMPDIR) + #os.rmdir(TEMPDIR) + except Exception, err: + if not reporterrors: + return + log().error(str(err)) + log().error("could not remove temporary diretory: %s! please delete by hand." % TEMPDIR) + sys.exit(1) + +def ExtractToTemp(filename): + file, extension = os.path.splitext(filename) + removetemp(False) + os.mkdir(TEMPDIR) + if extension.lower() == ".rar": + import UnRAR + dst = os.path.join(TEMPDIR, os.path.basename(filename)) + shutil.copyfile(filename, dst) + os.chdir(TEMPDIR) + UnRAR.Archive(os.path.basename(filename)).extract() + + # remove .rar file instantly + os.unlink(os.path.join(TEMPDIR, os.path.basename(filename))) + + # change back to current path + os.chdir(os.path.dirname(os.path.abspath(__file__))) + return True + elif extension.lower() == ".zip": + import UnZIP + UnZIP.unzip(filename, TEMPDIR) + return True + else: + log().info("copying "+filename+" to "+os.path.join(TEMPDIR, os.path.basename(filename))) + shutil.copyfile(filename, os.path.join(TEMPDIR, os.path.basename(filename))) + return False + +def installfile(maintarget, srcfile, dryrun): + file, extension = os.path.splitext(maintarget) + rorpath = getSettingsManager().getSetting("RigsOfRods", "BasePath") + + if extension in ['.truck', '.load']: + path = os.path.join(rorpath, "data", "trucks") + elif extension in ['.terrn']: + path = os.path.join(rorpath, "data", "terrains") + else: + path = rorpath + if dryrun: + log().info("would install %s to %s" % (os.path.basename(srcfile), path)) + else: + log().info("installing %s to %s" % (os.path.basename(srcfile), path)) + shutil.copyfile(srcfile, os.path.join(path, os.path.basename(srcfile))) + +def searchFile(filename, top): + for root, dirs, files in os.walk(top, topdown=False): + if filename in files: + return os.path.join(root, filename) + return None + +def getTargets(verbose): + import ror.depchecker + dc = ror.depchecker.RoRDepChecker(TEMPDIR, "getfiles", "", False) + targets = [] + for file in dc.files: + filename, extension = os.path.splitext(file) + if extension.lower() in ['.truck', '.terrn', '.load']: + targets.append(os.path.basename(file)) + + validtargets = [] + invalidtargets = [] + if len(targets) == 0: + log().info("### no targets found") + return validtargets, invalidtargets + + log().info("### found %d targets, checking them separatly now" % len(targets)) + for target in targets: + log().info("### checking target %s..." % target) + dc = ror.depchecker.RoRDepChecker(TEMPDIR, "dtree", target, verbose) + if dc.everythingfound: + validtargets.append(target) + else: + invalidtargets.append(target) + return validtargets, invalidtargets + +def getRoRMods(verbose): + import ror.depchecker + rorpath = getSettingsManager().getSetting("RigsOfRods", "BasePath") + dc = ror.depchecker.RoRDepChecker(rorpath, "getfiles", "", False) + targets = [] + for file in dc.files: + filename, extension = os.path.splitext(file) + if extension.lower() in ['.truck', '.terrn', '.load']: + targets.append(os.path.basename(file)) + newtargets = [] + md5s = dc.readMD5File() + for target in targets: + if not os.path.basename(target) in md5s.keys(): + newtargets.append(target) + return newtargets + + +def work(mode, targetfile, verbose, dryrun, installtarget=None): + log().info("### modinstaller started with %s, %s" % (mode, targetfile)) + if mode == "install": + filename = os.path.abspath(targetfile) + ExtractToTemp(targetfile) + target = installtarget + log().info("### validating target ...") + import ror.depchecker + dc = ror.depchecker.RoRDepChecker(TEMPDIR, "dtree", target, verbose) + if dc.invalid: + log().error("### target invalid!") + log().info("### please use the list mode to get valid targets") + usage() + + log().info("### target valid!") + #print dc.dstree + installcounter = 0 + for file in dc.dstree: + filename = file['filename'] + filenamefound = searchFile(filename, TEMPDIR) + if filenamefound is None: + log().error("File %s not found in %s!" % (filename, TEMPDIR)) + sys.exit(1) + installfile(target, filenamefound, dryrun) + installcounter += 1 + if dryrun: + log().info("### would install %d files." % installcounter) + else: + log().info("### %d files installed, finished!" % installcounter) + removetemp(False) + return [target] + + elif mode == "installall": + filename = os.path.abspath(targetfile) + ExtractToTemp(targetfile) + validtargets, invalidtargets = getTargets(verbose) + log().info("### installing %d found modifications:" % (len(validtargets))) + installcounter = 0 + for target in validtargets: + log().info("### installing modification '%s'" % target) + import ror.depchecker + dc = ror.depchecker.RoRDepChecker(TEMPDIR, "dtree", target, verbose) + if dc.dstree is None: + log().error("no dependenytree for File %s!" % (filename)) + continue + for file in dc.dstree: + filename = file['filename'] + filenamefound = searchFile(filename, TEMPDIR) + if filenamefound is None: + log().error("File %s not found in %s!" % (filename, TEMPDIR)) + sys.exit(1) + installfile(target, filenamefound, dryrun) + installcounter += 1 + if dryrun: + log().info("### would install %d files." % installcounter) + else: + log().info("### %d files installed, finished!" % installcounter) + removetemp(False) + return validtargets + + elif mode in ["list", "listall"]: + filename = os.path.abspath(targetfile) + ExtractToTemp(targetfile) + validtargets, invalidtargets = getTargets(verbose) + if mode == "listall": + if len(invalidtargets) > 0: + log().info("broken modifications found:") + for v in invalidtargets: + log().info(" %-20s" % v) + log().info("use the --verbose flag to find the missing files!") + else: + log().info("no broken modifications found") + + if len(validtargets) > 0: + log().info("installable modifications found:") + for v in validtargets: + log().info(" %-20s" % v) + else: + log().info("no installable modifications found! :(") + # todo : remove workaround! + removetemp(False) + return validtargets + + elif mode in ["listinstalled"]: + targets = getRoRMods(verbose) + if len(targets) > 0: + log().info("### Found Mods:") + for target in targets: + log().info(" "+target) + else: + log().info("### No Mods found!") + + if mode in ["uninstall"]: + rorpath = getSettingsManager().getSetting("RigsOfRods", "BasePath") + log().info("### validating target ...") + import ror.depchecker + dc = ror.depchecker.RoRDepChecker(rorpath, "dtree", targetfile, verbose) + if dc.invalid: + log().error("### target invalid! (Target not found)") + log().info("### please use the 'listinstalled' mode to get valid uninstallation targets") + return None + + log().info("### target valid!") + + #print dc.dstree + newtargets = [] + md5s = dc.readMD5File() + for file in dc.dstree: + filename = file['filename'] + if not os.path.basename(filename) in md5s.keys(): + newtargets.append(filename) + log().info("### removed %d files from dependency tree." % (len(dc.dstree)-len(newtargets))) + #print newtargets + if dryrun: + log().info("### would uninstall %d file(s):" % len(newtargets)) + else: + log().info("### uninstalling %d file(s):" % len(newtargets)) + for target in newtargets: + filenamefound = searchFile(target, rorpath) + if filenamefound is None: + log().error("### File not found: %s" % target) + continue + log().info(" %s" % filenamefound) + if not dryrun: + os.unlink(filenamefound) + + return None + +def usage(): + print "usage (general): %s <mode> <additionaloptions> [--verbose] [--dryrun]" % (os.path.basename(sys.argv[0])) + print "list <filename>" + print " list all found and valid modifications in filename" + print "" + print "listall <filename> --verbose" + print " list all found modifications in filename (valid and invalid)" + print "" + print "installall <filename> --verbose --dryrun" + print " install all found modifications in filename" + print "" + print "install <filename> <modification> --verbose --dryrun" + print " install a certain modifications in filename (valid and invalid)" + print "" + print "listinstalled" + print " lists all installed RoR Mods" + print "" + print "uninstall <modname> --verbose --dryrun" + print " uninstalls a mod" + print "" + print "notes: the --verbose option is optional to increase the output for debugging" + print " the --dryrun option is optional and prints out what would be done" + sys.exit(0) + +def main(): + + # check for valid RoR Directory! + import ror.settingsManager + rorpath = ror.settingsManager.getSettingsManager().getSetting("RigsOfRods", "BasePath") + if not os.path.isfile(os.path.join(rorpath,"RoR.exe")): + import ror.starter + ror.starter.startApp() + + if len(sys.argv) < 2: + usage() + + mode = sys.argv[1] + if not mode in ['list', 'listall', 'install', 'installall', 'listinstalled','uninstall']: + usage() + if len(sys.argv) < 4 and mode in ['install']: + usage() + + if mode in ['list', 'listall', 'install', 'installall']: + targetfile = sys.argv[2] + if not os.path.isfile(targetfile): + log().error("%s is not a valid target filename!" % targetfile) + usage() + elif mode in ['listinstalled']: + targetfile = rorpath + elif mode == 'uninstall': + targetfile = sys.argv[2] + + + + # get optional flags + verbose = False + dryrun = False + for option in sys.argv: + if option == "--verbose": + verbose = True + if option == "--dryrun": + dryrun = True + + # Import Psyco if available + try: + import psyco + psyco.full() + except ImportError: + pass + + if len(sys.argv) == 4: + installtarget = sys.argv[3] + else: + installtarget = None + work(mode, targetfile, verbose, dryrun, installtarget) + + + +if __name__=="__main__": + main() \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |