Compare commits

...

371 Commits

Author SHA1 Message Date
Tom Rothamel 01f82aaf4c Bump version. 2010-09-15 23:37:44 -04:00
Tom Rothamel 8b294e05ad Fix problem where if you hit quit, no at the main menu, the game starts. 2010-09-15 23:34:14 -04:00
Tom Rothamel 5b2fcb85e5 Fixed character not respecting the interact argument. 2010-09-15 22:34:29 -04:00
Tom Rothamel fb1d38dc3a Enter the with mode on with None. 2010-09-14 23:18:08 -04:00
Tom Rothamel 5cc6a8d75a Ensure that empty strings render with 0 width. 2010-09-13 23:22:58 -04:00
Tom Rothamel fbe2a03933 Normalize file line endings during updates. 2010-09-13 21:04:48 -04:00
Tom Rothamel 915bccf099 Fixed problem with modes (reported with patch by Spiky Catapillar.) 2010-09-12 23:52:08 -04:00
Tom Rothamel 0943e368e7 Fix mode to work with nvl and extend. 2010-09-12 23:48:39 -04:00
Tom Rothamel d35c6e190c Fix docs. 2010-09-09 11:37:34 -04:00
Tom Rothamel 1025ad5a6a Reduce size of updates. 2010-09-09 11:23:42 -04:00
Tom Rothamel fd74541318 Check that sayer is valid. 2010-09-09 11:23:24 -04:00
Tom Rothamel 821db477ae Update default enter/leave factories to work with offsets. 2010-09-09 10:06:40 -04:00
Tom Rothamel ed66034930 Fix bug that caused atl revolution not to work. 2010-09-09 09:58:30 -04:00
Tom Rothamel a9c91378fd Another version bump. 2010-09-08 22:17:48 -04:00
Tom Rothamel 1dc58f2ed1 Add AlphaDissolve to the tutorial. 2010-09-08 09:36:56 -04:00
Tom Rothamel ae916e2a59 More updater work. 2010-09-07 22:17:31 -04:00
Tom Rothamel f3af72e67e Properly notify on update events. 2010-09-07 21:52:45 -04:00
Tom Rothamel 939c2121b7 Fixes to updater. 2010-09-07 21:41:02 -04:00
Tom Rothamel 46699bfc1e Update copyright, and bump versions. 2010-09-07 21:19:54 -04:00
Tom Rothamel 63d381d5a6 FieldValues with max_is_zero set to True now work properly. Thanks to
SleepKirby for the fix.
2010-09-07 08:13:30 -04:00
Tom Rothamel c608d18684 Update distribution building to reflect new Windows layout. 2010-09-07 00:05:11 -04:00
Tom Rothamel c31f61e7b6 Integrate updater support w/ launcher. 2010-09-06 23:45:41 -04:00
Tom Rothamel 9912c15c04 Don't consider hidden screens when assigning default focus. 2010-09-06 14:19:07 -04:00
Tom Rothamel 651653593c Make MoveTransition respect offsets. 2010-09-06 12:52:29 -04:00
Tom Rothamel 85858974b8 Add urllib to dependencies. 2010-09-05 23:48:52 -04:00
Tom Rothamel a265fbb797 Fix problem with screen language lines numbers being in error. 2010-09-05 23:26:24 -04:00
Tom Rothamel e353ea2d56 Don't crash when compiling shaders. 2010-09-05 22:54:00 -04:00
Tom Rothamel 6f91db067a Fix a bug with hotbars not working.
Fix a bug caused by an incorrect texture unit check.
2010-09-05 18:32:49 -04:00
Tom Rothamel 8ed51cc810 Add renpy.notify and Notify. 2010-09-04 17:25:59 -04:00
Tom Rothamel f256f174f9 The new :func:HideInterface action allows the interface to
temporarily be hidden, as a screen language action.
2010-09-04 15:59:30 -04:00
Tom Rothamel 49d3796378 Added the :ref:renpy.focus_coordinates function, which returns the
coordinates of the currently focused displayable, when possible.
2010-09-04 15:46:30 -04:00
Tom Rothamel bfb6a18527 The new :ref:modes system allows one to invoke callbacks when
switching from one type of interaction to another. This can be used,
for example, to automatically hide the window before transitions.
2010-09-04 12:30:21 -04:00
Tom Rothamel 2960220a74 Improvements to updater. 2010-09-03 22:52:10 -04:00
Tom Rothamel c6605f1742 Add experimental update code. 2010-09-03 18:17:48 -04:00
Tom Rothamel cebffcfee1 Imagemaps created using the screen language now only have a size equal
to that of their ground image. (Previously, they took up the entire
screen.) This change makes it easier to position an imagemap at a
different location on screen, such as the bottom.

Imagemaps now take an alpha argument. If true (the default), hotspots
are only focused if the mouse is over a non-transparent part of the
idle or hover image. If set to false, the hotspot is focused whenever
the mouse is within its boundaries.
2010-09-03 17:42:46 -04:00
Tom Rothamel 006cdb8c3b The developer menu now includes a command that will list all the files
in the game directory.
2010-09-02 01:08:18 -04:00
Tom Rothamel 374e0697bf Fix documentation generation from curried functions. 2010-09-02 00:48:57 -04:00
Tom Rothamel f988878424 Transforms no longer cause a divide by zero exception when the zoom,
xzoom, or yzoom properties are 0.
2010-09-02 00:02:46 -04:00
Tom Rothamel e59b252dce Fix problems with scaling (and especially, switching back and forth
between GL and scaled SW modes.)
2010-08-31 16:36:00 -04:00
Tom Rothamel b2747914d8 Fix hotspot so that it properly handles insensitive and selected images. 2010-08-28 18:47:15 -04:00
Tom Rothamel 41aeb625f3 Try to fix backwards compatibility problem. 2010-08-24 21:55:20 -04:00
Tom Rothamel 4cfa8aa06c Document AlphaDissolve. 2010-08-24 21:51:42 -04:00
Tom Rothamel 8cb4a4e3b9 Merge alphadissolve. 2010-08-24 21:46:58 -04:00
Tom Rothamel 9a84c9715f Use 256 as the parameter - allows alphablend to use the full 8 bits of alpha
range.
2010-08-24 21:17:52 -04:00
Tom Rothamel 38538f1d9a Add AlphaBlend. 2010-08-24 02:33:29 -04:00
Tom Rothamel 6a42b2a107 Initial implementation of AlphaDissolve transition. 2010-08-24 02:20:38 -04:00
Tom Rothamel 486790b810 merge w/ renpy 2010-08-22 16:11:15 -04:00
Tom Rothamel 0e538e2261 Remove obsolete files.
Remove symlinks in documentation.
2010-08-22 16:08:03 -04:00
Tom Rothamel 9042fcca55 Redo the windows build process, so that no symlinks are involved, and so
that dlls are no longer bundled inside renpy.code.
2010-08-22 15:53:55 -04:00
Tom Rothamel 040035adbc Allow keymap to take a list of actions. 2010-08-21 11:58:32 -04:00
Tom Rothamel d72097de18 add comment 2010-08-19 13:23:27 -04:00
Tom Rothamel d9771bdade Draw mouse cursor in right place. 2010-08-19 13:01:20 -04:00
Tom Rothamel 07ca905373 Fix the parameters for define_screen. 2010-08-19 08:48:58 -04:00
Tom Rothamel ccd0d45a67 A sub-render should inherit alpha from the parent render. 2010-08-18 19:54:59 -04:00
Tom Rothamel 15a15870e7 Start of new updater code. 2010-08-18 18:11:09 -04:00
Tom Rothamel 28108c7796 Remove launcher1. 2010-08-18 12:30:05 -04:00
Tom Rothamel 171f388120 6.11.0k 2010-08-17 21:19:01 -04:00
Tom Rothamel bc50f171db Add transition parameters to Show and Hide. 2010-08-17 01:08:10 -04:00
Tom Rothamel ea4c955f1f Modal and zorder are now expressions. Note that this changes the signature to define_screen. 2010-08-16 02:22:54 -04:00
Tom Rothamel 27524457d0 Copy a screen when keeping it around after a hide, rather than modifying the original screen. 2010-08-16 01:53:51 -04:00
Tom Rothamel 01fe67cfa9 Fix problems with screens caused by renpy.transition being given None as an argument, by making it handle that case properly, rather than simply delegating to with_none. 2010-08-15 21:46:21 -04:00
Tom Rothamel f4d493465d Fix problem with iterating over a list that's changing. 2010-08-15 19:15:32 -04:00
Tom Rothamel 33cbe44390 Only call _hide on direct children of the screen. 2010-08-15 02:53:41 -04:00
Tom Rothamel 5214f08d1a Assign ids to displayables correctly.
Remove non-transitions from screens at hide-time.x
2010-08-15 01:50:46 -04:00
Tom Rothamel 608fc986c4 Now can hide screens by name and tag. 2010-08-15 00:39:01 -04:00
Tom Rothamel 779a96f97f Things in a screen without an on hide method go away once hidden. 2010-08-15 00:32:53 -04:00
Tom Rothamel faf48246d7 Don't let a hiding displayable pass along focus. 2010-08-14 20:10:10 -04:00
Tom Rothamel 81ec2a6c35 fix modal when hiding. 2010-08-14 19:12:56 -04:00
Tom Rothamel 803423f12b Was over-aggressive in combining screen and old_transfers - split them. 2010-08-14 17:17:11 -04:00
Tom Rothamel b384ee0381 Make the gl-test strings translatable. Bump version. 2010-08-14 13:29:41 -04:00
Tom Rothamel b8862d6b24 Add support for a "Graphics Acceleration" menu, which allows the user
to choose between software and opengl rendering.
2010-08-13 00:50:48 -04:00
Tom Rothamel dbfa4ed46d Fix problem where displayables on a screen of one name could inherit transforms and state from displayables on a screen of a different name. 2010-08-13 00:38:43 -04:00
Tom Rothamel d9eb999775 Report when a grid is overfull. 2010-08-11 16:30:43 -04:00
Tom Rothamel b4a9ca3f87 Tweaks to gltest.
FilePageNext grows a max argument.

Report screen errors better.
2010-08-11 16:25:31 -04:00
Tom Rothamel d087c86d1a Set correct variable when setting default afm time. 2010-08-10 22:08:14 -04:00
Tom Rothamel 0cfc7b25a6 Remove imagemap rectangle from the image picker. 2010-08-10 00:35:50 -04:00
Tom Rothamel 8f3c9bd2ba Cycle through OpenGL logfile. 2010-08-09 23:19:55 -04:00
Tom Rothamel 91c79cdac9 sl: add default statement. 2010-08-09 21:42:49 -04:00
Tom Rothamel 20e4e110ce Add a check for calling ui.interact inside itself. 2010-08-09 18:57:12 -04:00
Tom Rothamel 870d7ffe2c Try the opengl test twice. 2010-08-09 16:29:10 -04:00
Tom Rothamel 6ff88c914d Fix use of modal in docs. 2010-08-08 22:46:59 -04:00
Tom Rothamel 2a2078517f Only don't transition when failing to go to the game menu from the main
menu.
2010-08-08 22:33:27 -04:00
Tom Rothamel c09f697293 6.11.0i 2010-08-08 20:20:20 -04:00
Tom Rothamel a9e273a13d Document modal more precisely. 2010-08-07 14:53:50 -04:00
Tom Rothamel 592665aa9a Various fixes to cause modal displayables to work better. 2010-08-07 14:43:13 -04:00
Tom Rothamel 3745788f06 Store the OpenGL-giveup value on startup, and use it on a restart. 2010-08-07 10:59:18 -04:00
Tom Rothamel 52b09d8f4c Fix problems with y aspect ratio. 2010-08-07 10:47:22 -04:00
Tom Rothamel 32f25cdcec Fix problem with lint_play_sound. 2010-08-07 09:06:41 -04:00
Tom Rothamel 6f022a9b6a 6.11.0h 2010-08-07 08:52:31 -04:00
Tom Rothamel eea6970929 (doc) Clarify that the hide event isn't called on scene or context exit. 2010-08-07 07:59:41 -04:00
Tom Rothamel 35ecfd279f Tweak when we run the hide event. 2010-08-07 07:52:49 -04:00
Tom Rothamel 1f5c610843 Better logic before picking between adv and nvl windows. 2010-08-07 00:30:52 -04:00
Tom Rothamel 05f4c52c33 Always render to an alpha texture, for dissolve/imagedissolve in sw mode. 2010-08-06 12:27:54 -04:00
Tom Rothamel 326f773e75 Constrain drawing area using glViewport. 2010-08-06 02:08:03 -04:00
Tom Rothamel 2079b518a2 F11 now toggles fullscreen. 2010-08-04 01:15:20 -04:00
Tom Rothamel 70ed15e5ac Add If function. 2010-08-04 00:59:09 -04:00
Tom Rothamel f1d7fe0c73 Rename group -> style_group. 2010-08-03 22:59:53 -04:00
Tom Rothamel 08e4b9bafc Minor optimizations in GL code. 2010-08-03 22:22:01 -04:00
Tom Rothamel 56a0212316 Fix problem with mouse, when going fullscreen. 2010-08-03 22:17:09 -04:00
Tom Rothamel 5df6506191 Take file_prefix and file_suffix into account for lint. 2010-08-02 23:36:10 -04:00
Tom Rothamel 39779be980 Fix problems with lint and call. Humanize lint output. 2010-08-02 18:22:13 -04:00
Tom Rothamel bdacdddf14 Fix crash with shift+Y and generated styles. 2010-08-02 17:59:40 -04:00
Tom Rothamel 4b32337ef3 Command the mouse to be displayed once a second. 2010-08-02 17:58:01 -04:00
Tom Rothamel 4897d5b7a9 Ensure Ren'Py starts when the GL modules can't be loaded. 2010-08-02 12:29:58 -04:00
Tom Rothamel 6daa64facd Store and restore the windows size on a shift+R reload. 2010-08-02 12:19:31 -04:00
Tom Rothamel 07651e414d Ensure we always check for yesno_prompt. 2010-08-01 21:33:29 -04:00
Tom Rothamel 7e1e76f0d8 When loading textures, load the borders with adjacent pixels, rather than
transparency. This means we no longer have to distort textures when
upscaling, which improves quality.
2010-08-01 13:47:05 -04:00
Tom Rothamel b91a5d1a16 Check in keywords file. 2010-07-31 23:19:39 -04:00
Tom Rothamel 39b0646f24 Change around some things involving clip planes to try to fix a
problem with them on the mac.

6.11.0g
2010-07-31 21:08:58 -04:00
Tom Rothamel ea6406f144 When upscaling, adjust texture coordinates so that we never go outside
the loaded texture.
2010-07-31 13:30:23 -04:00
Tom Rothamel 7ed3f3fbad Add the quickstart to the manual. 2010-07-30 13:16:50 -04:00
Tom Rothamel cacb4ac40e Allow {fast} to work in menus and all-at-once mode. 2010-07-28 23:27:52 -04:00
Tom Rothamel 9503744631 Unbranding error messages. 2010-07-28 22:45:00 -04:00
Tom Rothamel 58dfd5dbfa Document focus, and use it to ensure that menus do not have any choice highlighted by default. 2010-07-28 22:40:48 -04:00
Tom Rothamel 60d5507184 Only call unhovered when a non-default unhover occurs. 2010-07-28 22:34:39 -04:00
Tom Rothamel 5641cec146 Give a proper error when someone tries to use an empty string as a displayable. 2010-07-28 22:32:51 -04:00
Tom Rothamel dd455e3d14 Fix problems with window hide / window show and NVL-mode. 2010-07-28 21:55:16 -04:00
Tom Rothamel 6876697f74 Fixed proble with default focus and subsurface. 2010-07-25 23:15:40 -04:00
Tom Rothamel 4373cab8cf 6.11.0f 2010-07-25 20:10:01 -04:00
Tom Rothamel eeccb5833b Doc fixes, remove AutoForward as an independent action. 2010-07-25 20:07:22 -04:00
Tom Rothamel 790dad0330 Fix / document screens. 2010-07-25 19:58:48 -04:00
Tom Rothamel 078a38af5d Pass transform events through to children of Transforms. 2010-07-25 13:55:44 -04:00
Tom Rothamel 8c186d2eb1 Remove extraneous print. 2010-07-25 13:40:04 -04:00
Tom Rothamel 81b94b27e0 Display problems documentation.
Limit display to screen size.
2010-07-25 01:15:20 -04:00
Tom Rothamel 17e8616e8c Do not buffer playback of movies.
Change get_playing to return audio that's queued up to play, as well as audio that's currently playing.
2010-07-24 16:44:39 -04:00
Tom Rothamel 50b0dc3c5e Add the ability to blacklist mugen's video card. 2010-07-24 13:24:49 -04:00
Tom Rothamel 9e217e722f Introduce StoreProxy object. 2010-07-24 11:41:22 -04:00
Tom Rothamel f466b44b66 Fix problem with negative line_spacing. 2010-07-23 02:32:31 -04:00
Tom Rothamel 34e0fc7cba Always take screenshots from the main thread. 2010-07-23 01:53:39 -04:00
Tom Rothamel bb88a7bb95 Remove letterboxing when taking a screenshot. 2010-07-23 01:14:06 -04:00
Tom Rothamel 71ba444e62 6.11.0e. 2010-07-18 10:39:09 -04:00
Tom Rothamel 3e0baee463 Update documentation. 2010-07-17 22:44:53 -04:00
Tom Rothamel a0064f5511 Disable OpenGL in launcher. 2010-07-17 22:37:01 -04:00
Tom Rothamel e7ce23f377 Fix potential video race. 2010-07-17 22:35:11 -04:00
Tom Rothamel 9c6d93968c Stop defining default in terms of other transforms, to allow those
transforms to be re-defined.
2010-07-17 22:00:21 -04:00
Tom Rothamel e4b29d58f4 Include indentation in text size. 2010-07-17 17:38:44 -04:00
Tom Rothamel a48b87a0d6 Fixed a bug that could cause ATL transforms to over-compute changes,
this leading to problems when used in parallel
2010-07-17 16:17:26 -04:00
Tom Rothamel 763515a937 Add GL Performance test. 2010-07-17 14:02:00 -04:00
Tom Rothamel 46a8242e51 Make sure that lexer revert also reverts the line. 2010-07-17 12:59:18 -04:00
Tom Rothamel efa8d66d3d Make placement of developer menu more friendly. 2010-07-15 23:28:37 -04:00
Tom Rothamel b7c71bb3b8 Work better with broken fonts. 2010-07-15 22:36:05 -04:00
Tom Rothamel aca5438b5a Use shift to disable OpenGL. Add deinit to swdraw. 2010-07-15 17:15:54 -04:00
Tom Rothamel e7eb23ab5e Create layout.yesno_screen function.
Doc update.

Bump to 6.11.0d.
2010-07-14 21:47:46 -04:00
Tom Rothamel 05dd8bfcc7 Use "screen" as the screen type and mouse for screens. 2010-07-14 20:39:30 -04:00
Tom Rothamel 2c299ab079 Share code between fullscreen and displayable versions of video playback. 2010-07-14 19:00:33 -04:00
Tom Rothamel 62acff5c75 CTRL on startup aborts OpenGL mode. 2010-07-14 01:22:40 -04:00
Tom Rothamel 316d146893 Make imagedissolve use the correct texture units. 2010-07-13 22:28:41 -04:00
Tom Rothamel e69fee2108 Auto-vivification of styles.
New styles.
2010-07-13 01:09:14 -04:00
Tom Rothamel 8fe6e1cf20 Add group argument to ui functions. 2010-07-13 00:27:48 -04:00
Tom Rothamel 6fcf7dbbba Blacklist Mesa Indirect GLX renderer. 2010-07-12 21:13:32 -04:00
Tom Rothamel f55c5f0ce5 Make screen language automatically prefix unicode-containing strings with u"" - like we do for other strings. 2010-07-12 20:42:32 -04:00
Tom Rothamel aaf8369421 Deallocate textures on shutdown. 2010-07-12 20:40:41 -04:00
Tom Rothamel 8e26c7730c Finish has rename.
Fix bugs with screens.
2010-07-11 22:46:19 -04:00
Tom Rothamel 556ca0611a Add has statement. 2010-07-11 17:25:46 -04:00
Tom Rothamel e2e78c175b Tweak the parser so that it recognizes \$ as a word unto itself. 2010-07-11 15:14:44 -04:00
Tom Rothamel 7b8033e6b2 A reference loop was preventing the weakref-based way of dealing with
PyCode from working. So instead, manually control when PyCodes are
recorded.
2010-07-11 13:04:44 -04:00
Tom Rothamel d602645fee Use button_text rather than default as the default button text style. 2010-07-11 11:57:06 -04:00
Tom Rothamel f8ac9c9e83 Bump version to 6.11.0c. 2010-07-10 16:06:22 -04:00
Tom Rothamel 98c90f8ab3 Shutdown trace.
Restrict minimum window size to 256x256.

Ensure window caption and icon are set when reiniting pygame.
2010-07-10 16:03:54 -04:00
Tom Rothamel 16bb21ee62 Always have an auto-forward length of 1. 2010-07-10 13:44:00 -04:00
Tom Rothamel 46bfec93d4 Set the window caption and icon whenenver we reinit the display. 2010-07-10 13:42:38 -04:00
Tom Rothamel 00e1ecf37d Fix DBZ protection. 2010-07-10 11:45:41 -04:00
Tom Rothamel a3e7b290fb Make references to PyCode weak, so that they are not compiled if they
do not live into the final game script.
2010-07-09 01:35:40 -04:00
Tom Rothamel 27ce59963f Document ui.detached, and make it work in an init block. 2010-07-09 01:02:10 -04:00
Tom Rothamel 54e3a97447 Play test sounds on the "sound" channel. 2010-07-09 00:36:41 -04:00
Tom Rothamel f886f710b7 Make video transient.
Fix most problems with ui.textbutton.
2010-07-09 00:06:30 -04:00
Tom Rothamel a895e1dc6c Always use copy RTT.
Deinitialize pygame on shutdown, and log that deinit, so we can notice where a crash there occurs.
2010-07-08 23:22:27 -04:00
Tom Rothamel 6f24d8eebd 6.11.0b 2010-07-07 19:40:03 -04:00
Tom Rothamel 000174c2c4 Implement renpy.get_renderer_info.
Change RENPY_DRAW -> RENPY_RENDERER.
2010-07-07 14:19:53 -04:00
Tom Rothamel 192aaea186 Make a click while AFM is enabled disable AFM. 2010-07-07 14:01:20 -04:00
Tom Rothamel eb0d6b696e Adds label and ui.label. 2010-07-07 02:42:40 -04:00
Tom Rothamel 94e1b0eb56 Update gl-screen when soft mouse moves. 2010-07-07 02:05:48 -04:00
Tom Rothamel 694a1cd6d5 Ensure we always project the mouse location into virtual coordinates. 2010-07-07 01:26:40 -04:00
Tom Rothamel 0600897a26 Check the number of texture units, and give up on OpenGL if less than 4. 2010-07-06 22:32:14 -04:00
Tom Rothamel e8c52f9417 Disable texture units w/o a texture bound to them. 2010-07-06 22:19:49 -04:00
Tom Rothamel 6d86963b1d Restart the video system when switching from GL to SW rendering. 2010-07-06 21:35:40 -04:00
Tom Rothamel 01e621067a Fix spelling error. 2010-07-06 12:11:03 -04:00
Tom Rothamel cd379ef1a3 Fix aspect ratio problem. 2010-07-06 11:07:20 -04:00
Tom Rothamel 41a4fbfb4d Rewrite icon changing to use the standard PEfile library.
Fix other bugs found through testing.
2010-07-05 22:25:48 -04:00
Tom Rothamel 04db2112c3 Rewrote Character and Text so that text is only parsed once. 2010-07-04 23:40:38 -04:00
Tom Rothamel d20bfb18bc Handle syntax errors in screen language code. 2010-07-04 16:44:20 -04:00
Tom Rothamel d02d83f896 Try to ensure that runtime errors in screen language code are
reported at the right location.
2010-07-04 02:25:31 -04:00
Tom Rothamel 6b45c92a58 Rewrite screenlang.py so that it generates and compiles python code
directly.
2010-07-03 13:58:25 -04:00
Tom Rothamel 871ad8c07f Ensure the screen reflects the end of a pause before the pause finishes.
Actually limit gl framerate.
2010-06-30 01:14:13 -04:00
Tom Rothamel 997290cd28 Work on improving screen speed. 2010-06-30 00:30:20 -04:00
Tom Rothamel fcfab5ada6 spelling fix 2010-06-29 02:23:13 -04:00
Tom Rothamel 005f45bad3 Stop Popen.__del__ from throwing errors on shutdown. 2010-06-28 23:48:46 -04:00
Tom Rothamel ef64872af5 Set the projects directory to None if it no longer exists. 2010-06-27 23:15:58 -04:00
Tom Rothamel 2cd5528df9 Take the condition parameter to Characters into account when scrying to
determine if the statement interacts.
2010-06-27 22:44:45 -04:00
Tom Rothamel 0a73e6f905 Stop sounds and movies on a rollback event. 2010-06-27 22:04:46 -04:00
Tom Rothamel b9f468e3f4 Update the license.
Fix a bar regression.

Ensure that slow_done always triggers, and the ctc indicator is always shown. (Fixes lp:520276)
2010-06-27 21:01:47 -04:00
Tom Rothamel ad5631ffc1 Fix bug 595532 - wrong text in tutorial game. 2010-06-27 18:40:25 -04:00
Tom Rothamel 50767c211a Sphinx style and indexing tweaks. 2010-06-27 18:11:44 -04:00
Tom Rothamel 8223545b72 Add sphinx ATL documentation. 2010-06-27 16:55:28 -04:00
Tom Rothamel 9925fa78e7 More documentation work. 2010-06-27 12:38:48 -04:00
Tom Rothamel 7834365803 Adding various changelogs. 2010-06-27 11:16:45 -04:00
Tom Rothamel 5bfeea6e30 Finish style documentation (for now at least). 2010-06-27 10:28:09 -04:00
Tom Rothamel 1877fcfe65 Link style lists from screens. 2010-06-27 02:23:36 -04:00
Tom Rothamel 98437bc207 Adding styles documentation. 2010-06-27 02:04:56 -04:00
Tom Rothamel 49e9560e91 Rename docs a bit more.
Add dlls to distribute.py files.
2010-06-25 01:56:09 -04:00
Tom Rothamel 9c5084ef14 Move doc directory.
Add automatic keyword generation support to examples.rpy.
2010-06-25 00:32:50 -04:00
Tom Rothamel 401c503c91 Mark the newest save file as selected.
Fix a problem with buttons showing up as insensitive during a transition.
2010-06-24 23:31:36 -04:00
Tom Rothamel 73d4515f9e Fix SaveMenu. 2010-06-24 22:09:13 -04:00
Tom Rothamel 9faadbd077 Fix tutorial game ATL.
Add renpy.list_files.
2010-06-24 21:05:32 -04:00
Tom Rothamel c886f16308 Change tutorial to deal with new Transform semantics.
Change DynamicDisplayable to be sure we can always get_position.
2010-06-24 11:01:10 -04:00
Tom Rothamel 6b4b410708 Ensure that we don't fail to set a transform's pos and anchor because
we're setting it to the old default value.
2010-06-24 08:46:51 -04:00
Tom Rothamel d6e50d840f pos and anchor are now considered part of the execution state of a
transform.
2010-06-24 01:26:59 -04:00
Tom Rothamel c1848159a9 The new LiveTile displayable tiles its child, without consuming a
large amount of memory to do so.
2010-06-23 23:49:36 -04:00
Tom Rothamel 46f503ec3c Wait until the adjustment is done being created before setting the
focusable property on a bar.
2010-06-23 22:05:05 -04:00
Tom Rothamel 71f40a33f7 Add the language basics document. 2010-06-23 21:05:33 -04:00
Tom Rothamel 94e789efde More windows distribution fixes. 2010-06-23 19:02:36 -04:00
Tom Rothamel d738da4272 Update build_exe and pefile to support python 2.6. 2010-06-23 18:52:38 -04:00
Tom Rothamel 8bbf9cb618 Update modules to build on Windows.
Read the surface masks out of a surface.
2010-06-23 15:49:35 -04:00
Tom Rothamel c5276e5073 Use a screen for the tutorial game tutorials menu.
Document viewport, add XScrollValue and YScrollValue.
2010-06-21 20:34:13 -04:00
Tom Rothamel 9b0a739872 Make bar actually respect a supplied style. 2010-06-20 22:55:54 -04:00
Tom Rothamel b3e817e1d4 Make subsurfaces depend on a surface. Fixes render leak bug. 2010-06-20 21:19:25 -04:00
Tom Rothamel 96a73712eb Try fixing a bug with masks on Linux. 2010-06-20 20:51:35 -04:00
Tom Rothamel dc91721ca2 Add config to doc. 2010-06-20 20:47:10 -04:00
Tom Rothamel 7175bb664c Tweak doc look. 2010-06-20 01:00:28 -04:00
Tom Rothamel 2a49120ac2 Add special screens. 2010-06-18 00:49:57 -04:00
Tom Rothamel 4ef546649b Document python mode. 2010-06-17 22:44:28 -04:00
Tom Rothamel f1a77bd2b0 Fix bug with old load/saves and invalid files.
Fix bug with screens and rollback.
2010-06-17 14:13:05 -04:00
Tom Rothamel aa8b6d364b Moved button and bar specialness into the displayables, rather than
the ui functions.

Changed the _replaces method to be a replaces constructor parameter.

Make the periodic method take st.

Add a periodic method to BarValue.

Implement AnimatedValue.
2010-06-17 12:56:04 -04:00
Tom Rothamel 1245c6120e Wrote a lot of screen documentation. 2010-06-15 23:32:03 -04:00
Tom Rothamel 2995118cae Re-implement subsurface clipping, to improve performance in some cases.
Make call scene (and renpy.call_scene) participate in rollback, roll
forward, and set _return as appropriate.
2010-06-15 13:40:37 -04:00
Tom Rothamel a201418d1a Implement is_pixel_opaque. 2010-06-15 11:54:36 -04:00
Tom Rothamel 1b46904897 Modify yesno_prompt so it uses actions, rather than interacting.
Add FileTakeScreenshot.
2010-06-15 00:42:10 -04:00
Tom Rothamel 1cf6764a08 Allow an input screen. 2010-06-15 00:09:47 -04:00
Tom Rothamel 6527b4e198 Implement screens for NVL-mode. 2010-06-14 23:48:45 -04:00
Tom Rothamel fd4d01374f Implement the show screen, hide screen, and call screen user-statements. 2010-06-14 11:08:31 -04:00
Tom Rothamel c77a11382d Rewrite parsing in terms of a trie, for flexibility and speed reasons. 2010-06-14 09:47:37 -04:00
Tom Rothamel 1239153a1c The distribution code has been moved into launcher/distribute.py. This
file can be run from the command line to build distributions in shell
scripts and other automated processes.

Plug games.renpy.org when building distributions.

Change xoffset and yoffset in transforms so that they stack with that
of the child.
2010-06-13 22:46:28 -04:00
Tom Rothamel ae7152a5fc The renpy.music.register_channel method now has two additional
parameters, file_prefix and file_suffix. These are prepended and
appended to filenames provided to the registered channel,
respectively.
2010-06-13 21:24:02 -04:00
Tom Rothamel eec4eb73b5 Added the rotate_pad transform property, which controls how Transform
pads rotated displayables. When set to False, _not_ the default, it's
now possible to rotate a (100, 50) displayable by 90 degrees, and have
the result be (50, 100) in size.
2010-06-13 19:51:02 -04:00
Tom Rothamel 0ab3521005 The screen language (and ui) now allows you to write action rather
than clicked.
2010-06-13 17:44:13 -04:00
Tom Rothamel 660ef587c9 Add mute preferences, and SetDict/ToggleDict to support them.
Add InvertSelected.
2010-06-13 16:47:13 -04:00
Tom Rothamel 541dd7b3c3 Implement _replaced on various displayables (Text, Input, Timer, and Viewport).
Implement _ctc screen.
2010-06-13 15:19:53 -04:00
Tom Rothamel ca53e2f696 Implement the basic framework for _replaces, which is called when
one widget replaces another as part of a screen.
2010-06-13 11:54:10 -04:00
Tom Rothamel 80764e130f Make opengl logging flush the file on each write.
Make opengl fullscreen quit and reinit the video system, so that we
can properly read out the size of the desktop.
2010-06-11 22:46:55 -04:00
Tom Rothamel 6afd0120c1 Add the screenshot action. 2010-06-10 22:21:23 -04:00
Tom Rothamel 953be074f2 The config.screenshot_crop configuration variable controls the area of
the screen that it stored when the user presses the screenshot key.
2010-06-10 22:16:19 -04:00
Tom Rothamel 03781d24d6 Ensure that actions only run when they are sensitive.
Ensure we can have more than one yesno_prompt up at a time.

Add CallInNewContext.

Make the inspector show things on the screens layer.
2010-06-10 22:01:41 -04:00
Tom Rothamel 55d87064a8 config.game_menu_action allows one to specify an action that is run
when entering the game menu.
2010-06-10 20:54:35 -04:00
Tom Rothamel 512478b945 Allow the user to specify an action that is run when someone hits the
quit button. (The one in the upper-right corner of the screen.)
2010-06-10 20:45:18 -04:00
Tom Rothamel 1c19ca8062 Add yes/no prompting. 2010-06-10 09:22:47 -04:00
Tom Rothamel fc764b464d ui.add can now take transform properties as keyword arguments. If at least
one transform property is present, ui.add will create a transform that
wraps the displayable it's adding to the screen.
2010-06-09 08:56:54 -04:00
Tom Rothamel 945b4fc1cd Add python statement (short and long forms) to screen language.
Change include statement to use statement.
2010-06-09 08:32:22 -04:00
Tom Rothamel 902b17462e Implement loading and saving using Actions, and various improvements
to screens, screen language, and ui to make sure we can pull off a
sensible implementation.
2010-06-09 00:27:54 -04:00
Tom Rothamel 8b0b39829a Use renpy.context()._main_menu rather than main_menu; ensure the former is always set. 2010-06-08 01:35:04 -04:00
Tom Rothamel 356ca9cd1e Implement the Play, Queue, and Stop actions, which control music/sound/etc.
Add a periodic method to actions, which is called on a periodic basis
while a button has that action.
2010-06-08 01:04:05 -04:00
Tom Rothamel 634da84442 Implement yesno_prompt for Quit and MainMenu, make ShowMenu-shown
screens transient, and clear out the screens when we enter a new
context.
2010-06-08 00:20:17 -04:00
Tom Rothamel 1d109ddaee Implement the Preference action/value constructor. 2010-06-07 23:37:01 -04:00
Tom Rothamel c1f996da07 Various fixes required to allow a working SL preferences screen. 2010-06-07 02:08:18 -04:00
Tom Rothamel b14c9f8954 Change ShowMenu so that it takes a short screen name, without the
"_screen" suffix.
2010-06-07 00:55:19 -04:00
Tom Rothamel 126050b4f3 Able to display an operational imagemap screen based main menu.
Rewrote screens so they are now use single word names, with an
optional explicit tag parameter.
2010-06-07 00:09:54 -04:00
Tom Rothamel 313e417f28 The choice screen allows in-game menus to be defined using screens. 2010-06-05 23:32:54 -04:00
Tom Rothamel e98ef1025c Implement more Actions and BarValues.
Ensure the say screen still works.
2010-06-05 23:02:46 -04:00
Tom Rothamel 3729e4bc3a sl: Ensure execution errors are reported in a relevant location. 2010-06-05 16:16:13 -04:00
Tom Rothamel ac071777ad Implement BarValue. 2010-06-05 01:15:59 -04:00
Tom Rothamel 445972756d sl: add on statement. 2010-06-04 01:22:32 -04:00
Tom Rothamel 91732e7def sl: Implement the for statement. 2010-06-03 01:25:38 -04:00
Tom Rothamel 5b7e4af26c Add key, timer, and transform statements to ATL. 2010-05-29 23:24:55 -04:00
Tom Rothamel 2bb459cda5 screen: Implement support for transient screens. 2010-05-28 23:03:16 -04:00
Tom Rothamel d410c73074 screen: refactor screens into Screen and ScreenDisplayable classes. 2010-05-28 08:59:08 -04:00
Tom Rothamel da70f197fe screen, sl: add zorder parameter. 2010-05-27 23:03:33 -04:00
Tom Rothamel c18ffb28d0 Pass transform events to the children of a screen. Allow the screen to
respond to a hide event.
2010-05-27 21:56:02 -04:00
Tom Rothamel d5f17ef9f1 Events propagate to all children. 2010-05-25 23:42:54 -04:00
Tom Rothamel 79c3f426e5 sl: Add xmaximum and ymaximum to the list of properties we support. 2010-05-25 23:02:29 -04:00
Tom Rothamel b004dd138f Add code for customizing the say screen. 2010-05-25 22:47:58 -04:00
Tom Rothamel 45b479e324 sl: implement if statement.
screen: trigger a redraw on each interaction.
2010-05-23 22:50:22 -04:00
Tom Rothamel b07cbd4193 sl: add include statement. 2010-05-23 21:58:00 -04:00
Tom Rothamel ae2739f32d Hooked up the screen language to the screen system. 2010-05-23 20:43:37 -04:00
Tom Rothamel dd51fcb1fd Fix ui.at, get things going with visit. 2010-05-22 22:07:58 -04:00
Tom Rothamel edc26fe0a4 First working screens. 2010-05-22 19:16:08 -04:00
Tom Rothamel c9215b3b71 Add renpy.ui.remove_above, for use by screens. (Not sure I'll bother
publically documenting this.)

Improve documentation of Scene Lists.
2010-05-16 01:06:13 -04:00
Tom Rothamel 115338bdeb Basic initial implementation of screens.
Rewrote the scene lists. This added support for "replaced" images, but
more importantly, cleaned up the code quite a bit, by making it be in
terms of objects rather than tuples.
2010-05-15 20:24:28 -04:00
Tom Rothamel b0b10ac7d3 Add all existing ui functions to the screen language parser. 2010-05-11 23:42:51 -04:00
Tom Rothamel 5a6013aac9 Update changelog.
Tweak config.default_transform behavior so that it only applies to
non-transforms, so we better match the old behavior.

fix renpy.ui.Many to work with with.
2010-05-04 01:58:10 -04:00
Tom Rothamel f3aa299aa0 Remove obsolete files from the gl-renpy branch. 2010-05-04 01:30:19 -04:00
Tom Rothamel 8e44536133 Merge in changes from old mainline. 2010-05-04 01:27:59 -04:00
Tom Rothamel 0cb937298e Add checkmark background when the screen is left empty, with no background.
Fix backwards compatibility bugs.
2010-05-04 01:26:01 -04:00
Tom Rothamel 6ed0491520 Add hotbars. 2010-05-02 00:27:58 -04:00
Tom Rothamel af7748920c Add hotspots. 2010-05-01 22:55:51 -04:00
Tom Rothamel 3c1c0310d8 Merge in screen language changes. 2010-04-30 01:29:57 -04:00
Tom Rothamel 91a67304dd Rewrite the ui module in terms of wrapper code. 2010-04-30 01:28:37 -04:00
Tom Rothamel 04d0e46c3e Rewrite how things are added in renpy.ui. 2010-04-29 01:08:10 -04:00
Tom Rothamel ed27eac80b Added support for composite style properties, that allow several style
properties to be set using a single parameter. The new composite style
properties are:

* pos - takes a pair, and uses it to set xpos and ypos.
* anchor - takes a pair, and uses it to set xanchor and yanchor.
* align - takes a pair, and uses it to set xalign and yalign. (And
  hence xpos, ypos, xanchor, and yanchor.)
* area - take (x, y, height, width) pair, and tries to set properties
  such that the displayable will be placed inside the rectangle. This 
  sets the xpos, ypos, xanchor, yanchor, xfill, yfill, xminimum, yminimum,
  xmaximum, and ymaximum properties.
2010-04-28 01:19:45 -04:00
Tom Rothamel 1f3e02bbdc More SL parsing. 2010-04-28 00:31:02 -04:00
Tom Rothamel 275e938602 Snapshot of work on screen system. 2010-04-27 00:24:33 -04:00
Tom Rothamel 3f80320d37 The python compiler has been rewritten to use the python ast module.
This should both improve performance, and improve error handling for
python syntax.
2010-04-23 23:12:11 -04:00
Tom Rothamel 0e44ce7636 Update docs. 2010-04-23 22:06:24 -04:00
Tom Rothamel 8fe727a8a1 Start on sphinx documentation for build system. 2010-04-18 01:51:17 -04:00
Tom Rothamel b82f7a5548 Use default_transform as the main way of positioning images on the screen. 2010-04-17 12:15:27 -04:00
Tom Rothamel fe15242479 Allow the position properties to be specified independently when transforms are composed. 2010-04-17 00:44:06 -04:00
Tom Rothamel 677a9b0dab Transform (and ui.transform) have been changed so that their arguments
can now be prefixed with a style prefix. One can write
ui.transform(idle_rotate=30, hover_rotate=90) and have it work. [doc]
2010-04-13 23:57:37 -04:00
Tom Rothamel 309001e2fe Pick mask based on platform. Fixes a bug in ubuntu 10.4 beta. 2010-03-30 02:06:25 -04:00
Tom Rothamel 90e782c9c6 Actually put textures on the free-lists, so we can reuse them. 2010-03-23 00:03:15 -04:00
Tom Rothamel f95d9cacb5 Sleep to prevent swdraw from speeding up the CPU. 2010-03-17 11:34:44 -04:00
Tom Rothamel 308d1e6b00 Choose directory for opengl.txt. 2010-03-17 11:16:23 -04:00
Tom Rothamel c57b3004a0 Reset display after renpygame. 2010-03-17 11:12:11 -04:00
Tom Rothamel 00bd5c96e9 Shift-reload now works in GL mode. 2010-03-16 22:08:45 -04:00
Tom Rothamel 371b11370a Allow Ren'Py to keep working even if GL can't be loaded. 2010-03-16 10:13:49 -04:00
Tom Rothamel b9338a7446 Video support. 2010-03-16 01:54:05 -04:00
Tom Rothamel e39ae375f4 Refactor things so texture caching takes place in the draw modules, using
weak references.
2010-03-15 13:24:48 -04:00
Tom Rothamel 975907aebf Fixed spelling, thanks to ZeikJT. 2010-03-15 00:45:51 -04:00
Tom Rothamel ccfbdf6f3a Software mouse works in GL Ren'Py. 2010-03-15 00:42:55 -04:00
Tom Rothamel 7934d40b7c Refactor mouse code. 2010-03-15 00:21:45 -04:00
Tom Rothamel 3b569a10bd Implement screenshots. 2010-03-14 16:49:11 -04:00
Tom Rothamel 941d959ee5 Reinitialize OpenGL (except for various detection) each time the window
is resized. This allows us to work on Mac OS X, which can't share any 
OpenGL state through a window resize. (At least with SDL+Pygame.)
2010-03-13 21:20:13 -05:00
Tom Rothamel d5a51c8139 Implement pixellate in gl-mode. 2010-03-13 19:01:46 -05:00
Tom Rothamel fc79078d51 Implement RENPY_GL_VSYNC, which control OpenGL vertical sync. 2010-03-13 12:42:43 -05:00
Tom Rothamel d6615410dd Allow the user to resize the GL window by dragging (or hitting the maximize
button).
2010-03-13 12:34:30 -05:00
Tom Rothamel adee372b4b Always add a left border to images. 2010-03-13 02:06:25 -05:00
Tom Rothamel 9c7542a357 Track total texture size. 2010-03-12 01:17:21 -05:00
Tom Rothamel bc18285a61 Allow renpy_draw to pick between software and hardware rendering. 2010-03-12 00:46:53 -05:00
Tom Rothamel 7b6c3f52e0 Implement imageblend. 2010-03-12 00:30:15 -05:00
Tom Rothamel f95c6e479d Add an extra row and column of pixels to textures that aren't full, to
ensure we don't interpolate in junk during subpixel rendering.
2010-03-11 21:47:27 -05:00
Tom Rothamel e4e224348f Merge premultiplied textures. 2010-03-11 01:50:59 -05:00
Tom Rothamel 7e914da261 Initial writing of premultiplied textures. 2010-03-11 01:49:33 -05:00
Tom Rothamel ae3eb40a0e Code to read from FB to surface.
Fix shaders to handle alpha blending.
2010-03-10 22:19:48 -05:00
Tom Rothamel 2f8cd81870 Dissolve works (with copy RTT). FBO rtt is buggy. 2010-03-09 23:50:55 -05:00
Tom Rothamel a1e7b60dab Implement basic render-to-texture.
Implement non-aligned clipping.
2010-03-09 17:02:12 -05:00
Tom Rothamel 92515fca49 Implement aligned clipping. 2010-03-09 02:27:41 -05:00
Tom Rothamel 6a8abf2a79 Basic support for clipping using glClipPlane. 2010-03-09 01:24:52 -05:00
Tom Rothamel 9a47b02840 Allocate texture numbers in the GL thread. 2010-03-08 18:49:19 -05:00
Tom Rothamel 488c1c34cd Use the right direction for the transform. 2010-03-08 02:03:42 -05:00
Tom Rothamel 52bd7de14f First drawing via GL to the screen. 2010-03-08 01:36:36 -05:00
Tom Rothamel deb0f813ca Making progress towards getting gl-drawing working. 2010-03-07 18:46:00 -05:00
Tom Rothamel 5030513375 Rewrite the text handling to create textures. 2010-03-06 20:16:55 -05:00
Tom Rothamel 53deb04137 Rewrite im to use textures instead of surfaces directly.
Add support for textures (really just surfaces) to swdraw.

Move rle cache code into swdraw.
2010-02-28 23:01:58 -05:00
Tom Rothamel 2c60f5251f Rewrite RotoZoom in terms of Transform. 2010-02-26 14:47:33 -05:00
Tom Rothamel 64ac5a9317 Rewrote Zoom, FactorZoom, and SizeZoom in terms of Renders. 2010-02-26 01:33:10 -05:00
Tom Rothamel 607113b31c Move pixellate into swdraw. 2010-02-24 21:47:32 -05:00
Tom Rothamel 5a472ef44b Finished factoring out dissolve and imagedissolve. 2010-02-24 01:28:27 -05:00
Tom Rothamel c67ba9b4e4 Restructured dissolve and imagedissolve. 2010-02-24 01:04:11 -05:00
Tom Rothamel 3f36d3a881 get_parameterized -> _get_parameterized 2010-02-24 01:03:10 -05:00
Tom Rothamel d188618785 Sync with main branch. 2010-02-23 16:31:25 -05:00
Tom Rothamel e6827bdff8 * lp:526297 - im.Rotozoom()s crash when Ren'Py is scaled down. (Thanks to Spiky Caterpillar for the bug report and fix.)
Renamed the internal show and hide methods of Displayable, so those
names can once again be used by user-defined displayables.
2010-02-23 15:12:44 -05:00
Tom Rothamel 85ac26fb1e Move the drawing code from render.py to swdraw.py. Now, none of the
code in render.py should be software-renderer specific.
2010-02-23 01:52:33 -05:00
Tom Rothamel abea49df8e Massive restructuring of the display system. The methods in Display
were split between the new SWDraw class and Interface. The idea is to
separate the software renderer out from the common code.
2010-02-23 01:13:02 -05:00
Tom Rothamel bfc7de0d16 glcore -> gldraw 2010-02-22 22:05:35 -05:00
Tom Rothamel aa8c3ecec9 Move gl stuff into the display directory. 2010-02-22 22:02:11 -05:00
Tom Rothamel 7ab984972e Started work on glcore.py. 2010-02-22 21:55:57 -05:00
Tom Rothamel da09c4d04f Implement the subsurface operation. 2010-02-21 20:02:31 -05:00
Tom Rothamel c42457446f Implemented a shader-based GL environment. 2010-02-21 02:35:30 -05:00
Tom Rothamel 40bb6ca557 Can compile shaders. 2010-02-20 23:25:58 -05:00
Tom Rothamel f2cc5d25e8 Implement render-to-texture using EXT_framebuffer_object, with
acceptable performance on both Nvidia and 950.
2010-02-20 13:50:49 -05:00
Tom Rothamel 04a5460e8b Init rtt and environ in a function, so we don't have to wait for them. 2010-02-20 11:04:20 -05:00
Tom Rothamel 12ef8ee199 Refactor render-to-texture code into a class, so we can have an
alternative implementation of it.
2010-02-20 02:41:26 -05:00
Tom Rothamel 9c2d2f3a06 Implement render to texture.
Implement (GL 1.1) blank texture loading.

Add EXT_framebuffer_object to tegl.
2010-02-19 19:56:11 -05:00
Tom Rothamel 94bcfe5c58 Change to using BGRA textures for speed on Nvida chips.
Make work on the mac.
2010-02-18 10:41:22 -05:00
Tom Rothamel fecd13c733 Allow textures of various sizes, from 512 to 64 pixels. 2010-02-17 22:54:43 -05:00
Tom Rothamel a9a6595d43 Implemented fixed-function imageblend. Also, tweaked normal blend so
textures are taken in the right order.
2010-02-16 00:20:02 -05:00
Tom Rothamel e4e9ea4e87 Working blend operation. 2010-02-14 21:14:29 -05:00
Tom Rothamel 588682f0d2 Change the representation of texgrids to include a tile index, rather
than implying the tile index.

Work on environments continues.
2010-02-14 19:17:32 -05:00
Tom Rothamel 0b502d5530 C-accelerated the rectangle drawing code. 2010-02-13 23:53:27 -05:00
Tom Rothamel 86a2b5d4e5 Move the GL setup code into a module. 2010-02-13 20:05:12 -05:00
Tom Rothamel 312a657e78 Rename surface.py to gltexture.py 2010-02-11 20:00:32 -05:00
Tom Rothamel 6197597ec9 Can now draw a TextureGrid to the screen. 2010-02-11 19:35:19 -05:00
Tom Rothamel c3ee29a9b0 Work on loading textures. 2010-02-11 09:01:42 -05:00
Tom Rothamel d5b26aa973 Work on loading textures. 2010-02-11 08:58:36 -05:00
Tom Rothamel 5d926ad49b Build modules in module directory. 2010-02-10 00:38:44 -05:00
Tom Rothamel b5f133ce17 Have working direct transfer of SDL surface -> texture. 2010-02-09 00:32:01 -05:00
Tom Rothamel 6ee4474e5e Prevent completing a rollback from triggering an exception if
other code is updating objects that it uses.
2010-02-07 13:06:58 -05:00
Tom Rothamel d515d07110 Customized TEGL for our purposes. 2010-02-04 20:58:57 -05:00
Tom Rothamel 3d2e5124d4 Add a clean tegl. 2010-02-04 20:50:51 -05:00
Tom Rothamel 48a826a13d Fix bug that could cause last element of a MultipleTransition to show twice. 2010-02-04 16:53:57 -05:00
Tom Rothamel 64e82c2c62 Rewrote MultipleTransition (which is used by Fade) to fix some
problems it was exhibiting.
2010-02-04 15:43:21 -05:00
Tom Rothamel 9c5d4d7ad5 Do not query volume if a mixer is disabled, in the imagemap
preferences screen.
2010-01-26 20:42:17 -05:00
Tom Rothamel 5f006c8f4c Bump version. 2010-01-22 11:00:07 -05:00
Tom Rothamel 3d8b6cbecb Remove default_transform test code that got stuck in a release. 2010-01-22 10:56:36 -05:00
172 changed files with 44644 additions and 8768 deletions
+10 -1
View File
@@ -49,7 +49,6 @@ renpygame-1.2.zip
speedtest
styles.txt
renpygame-demo/game/saves
./lib
Lucy Sprites.zip
translate
close_bugs.py
@@ -58,3 +57,13 @@ scite-6.10.zip
scite-renpy-20090803.zip
module/cython.sh
old_demo
opengl.txt
Microsoft.VC90.CRT.manifest
console.exe
msvcr90.dll
python26.dll
renpy.exe
lib/windows-x86
sphinx/source/inc/*
doc/*
updates/prerelease
+1
View File
@@ -1,3 +1,4 @@
New in Ren'Py 6.10.2
--------------------
+711 -669
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -5,6 +5,8 @@ if [ "x$1" = "x" ]; then
exit
fi
rsync -av updates tom@onegeek.org:/home/tom/WWW.update/renpy/
mkdir ~/ab/website/renpy/dl/$1
cp dists/renpy-$1-* ~/ab/website/renpy/dl/$1
cp CHANGELOG.txt ~/ab/website/renpy/dl/$1
+35 -8
View File
@@ -1,21 +1,36 @@
#!/usr/bin/env python
import shutil
from distutils.core import setup
import py2exe
import sys
import zipfile
import traceback
import os
# The pythonpath on my system.
sys.path.insert(0, 'c:\\msys\\1.0\\newbuild25\\install\\bin')
sys.path.insert(0, 'c:\\msys\\1.0\\newbuild25\\install\\python')
sys.path.insert(0, 'c:\\msys\\1.0\\newbuild\\install\\bin')
sys.path.insert(0, 'c:\\msys\\1.0\\newbuild\\install\\python')
def move_from_dist(fn):
"""
Moves the file `fn` from the dist directory to the main
directory. (This means we don't need symlinks on windows.)
"""
if os.path.isdir(fn):
shutil.rmtree(fn)
elif os.path.exists(fn):
os.unlink(fn)
os.rename("dist/" + fn, fn)
def main():
sys.argv[1:] = [ 'py2exe', '--bundle', '2', '-a', '--dll-excludes', 'w9xpopen.exe', ]
# sys.argv[1:] = [ 'py2exe', '-a', '--dll-excludes', 'w9xpopen.exe', ]
sys.argv[1:] = [ 'py2exe', '-a', '--dll-excludes', 'w9xpopen.exe', ]
setup(name="RenPy",
setup(name="Ren'Py",
windows=[ dict(script="renpy.py",
dest_base="renpy",
icon_resources=[ (1, "newicon.ico") ],
@@ -24,7 +39,7 @@ def main():
console=[ dict(script="renpy.py", dest_base="console") ],
zipfile='renpy.code',
zipfile='lib/windows-x86/renpy.code',
options={ 'py2exe' : { 'excludes' : [ 'doctest',
'pygame.macosx',
@@ -48,8 +63,8 @@ def main():
)
zfold = zipfile.ZipFile("dist/renpy.code")
zfnew = zipfile.ZipFile("renpy.code", "w", zipfile.ZIP_STORED)
zfold = zipfile.ZipFile("dist/lib/windows-x86/renpy.code")
zfnew = zipfile.ZipFile("dist/lib/windows-x86/renpy.code.new", "w", zipfile.ZIP_STORED)
seen = { }
@@ -70,6 +85,18 @@ def main():
zfold.close()
zfnew.close()
os.unlink("dist/lib/windows-x86/renpy.code")
os.rename("dist/lib/windows-x86/renpy.code.new", "dist/lib/windows-x86/renpy.code")
shutil.copy("c:/Python26/Microsoft.VC90.CRT.manifest", "Microsoft.VC90.CRT.manifest")
shutil.copy("c:/Python26/msvcr90.dll", "msvcr90.dll")
move_from_dist("lib/windows-x86")
move_from_dist("console.exe")
move_from_dist("python26.dll")
move_from_dist("renpy.exe")
try:
main()
except:
-84
View File
@@ -1,84 +0,0 @@
1#!/usr/bin/env python
import collections
import glob
import re
import sys
import time
# A map from string to filename, line number where the string is found.
strings = collections.defaultdict(list)
def process(fn):
lineno = 0
for data in file(fn, "r"):
lineno += 1
matches = [ ]
matches += re.finditer(r'\bu\"(\\"|[^"])+\"', data)
matches += re.finditer(r"\bu\'(\\'|[^'])+\'", data)
for m in matches:
s = m.group(0)[2:-1]
if "\\u" in s:
continue
if len(s) == 1:
continue
strings[s].append("%s:%d" % (fn, lineno))
if __name__ == "__main__":
files = [ ]
files += glob.glob("launcher2/*.rpy")
files += glob.glob("common/*.rpy")
files += glob.glob("common/_layout/*.rpym")
files += glob.glob("common/_compat/*.rpym")
for fn in files:
process(fn)
converse = [ ]
for k, v in strings.iteritems():
v = " ".join(sorted(v))
converse.append((v, k))
converse.sort()
print """\
# Ren'Py Visual Novel Engine
# Copyright (C) 2009 PyTom <pytom@bishoujo.us>
# This file is distributed under the same license as the Ren'Py package.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: mainline\\n"
"Report-Msgid-Bugs-To: PyTom <pytom@bishoujo.us>\\n"
"POT-Creation-Date: %s\\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n"
"Language-Team: LANGUAGE <LL@li.org>\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
""" % time.strftime("%Y-%m-%d %H:%M%z")
for v, k in converse:
print
print "#:", v
print "#, python-format"
print "msgid \"%s\"" % k
print "msgstr \"\""
+14
View File
@@ -29,7 +29,21 @@ init -1210 python:
store.offscreenleft = Position(xpos=0.0, xanchor=1.0)
store.offscreenright = Position(xpos=1.0, xanchor=0.0)
if version <= (6, 10, 2):
# Before 6.11, we used the image placement to handle
# the location of things on the screen.
style.image_placement.xpos = 0.5
style.image_placement.ypos = 1.0
style.image_placement.xanchor = 0.5
style.image_placement.yanchor = 1.0
config.transform_uses_child_position = False
config.default_transform = None
config.start_scene_black = True
if version <= (6, 11, 0):
config.movetransition_respects_offsets = False
init 1210 python hide::
+4 -7
View File
@@ -35,20 +35,17 @@ init -1110:
xpos 1.0 xanchor 0.0 ypos 1.0 yanchor 1.0
transform default:
reset
center
alpha 1 rotate None zoom 1 xzoom 1 yzoom 1 align (0, 0) alignaround (0, 0) subpixel False size None crop None
xpos 0.5 xanchor 0.5 ypos 1.0 yanchor 1.0
python:
config.default_transform = right
config.default_transform = default
init -1110 python:
_define = define = object()
# Positions ##############################################################
# Transitions ############################################################
# Simple transitions.
@@ -193,4 +190,4 @@ init 1110 python:
# This is necessary to ensure that config.default_transform works.
if config.default_transform:
config.default_transform.show()
config.default_transform._show()
+180
View File
@@ -0,0 +1,180 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
# See LICENSE.txt for license details.
# This contains code to choose between OpenGL and Software rendering, when
# a system supports both.
init -1024:
screen _gl_test:
frame:
xalign .5
yalign .33
xpadding 20
ypadding 20
has vbox
label _(u"Graphics Acceleration")
null height 10
textbutton _(u"Automatically Choose"):
size_group "gl"
action SetField(persistent, "_gl_test", "auto")
textbutton _(u"Prefer Software Renderer"):
size_group "gl"
action SetField(persistent, "_gl_test", "sw")
textbutton _(u"Prefer OpenGL Renderer"):
size_group "gl"
action SetField(persistent, "_gl_test", "gl")
null height 10
textbutton _(u"Continue"):
size_group "gl"
action Return(True)
init -1024 python:
# The image that we fill the screen with in GL-test mode.
config.gl_test_image = "black"
class __GLTest(renpy.Displayable):
"""
This counts the number of times it's been rendered, and
the number of seconds it's been displayed, and uses them
to make the decisions as to if OpenGL is working or not.
"""
def __init__(self, frames, fps, timeout):
super(__GLTest, self).__init__()
self.target = 1.0 * frames / fps
self.frames = frames
self.timeout = timeout
self.times = [ ]
self.success = False
def render(self, width, height, st, at):
self.times.append(st)
renpy.redraw(self, 0)
if len(self.times) >= self.frames:
if (self.times[-1] - self.times[-self.frames]) < self.target:
self.success = True
renpy.timeout(0)
rv = renpy.Render(width, height)
return rv
def event(self, ev, x, y, st):
if self.success:
return True
if st > self.timeout:
return False
renpy.timeout(self.timeout - st)
def __gl_prefer_renderers(renderers):
"""
Forces the current renderer to be renderer, one of gl or sw.
"""
if renpy.display.prefer_renderers == renderers:
return
renpy.display.prefer_renderers = renderers
renpy.display_reset()
def __gl_prompt():
"""
Decides if we want to prompt the user to enable OpenGL mode.
If so, shows a screen that allows the user to alter the
OpenGL setting.
"""
if not renpy.display.interface.safe_mode:
return
__gl_prefer_renderers("sw")
renpy.call_screen("_gl_test")
renpy.display.interface.safe_mode = False
def __gl_test():
"""
Makes the decision as to if we should use GL or SW mode.
"""
import os
if "RENPY_RENDERER" in os.environ:
return
# Our decision survives a restart.
if _restart:
return
# If GL is disabled, don't bother.
if not config.gl_enable:
return
__gl_prompt()
if persistent._gl_test == "gl":
__gl_prefer_renderers("gl,sw")
return
if persistent._gl_test == "sw":
__gl_prefer_renderers("sw")
return
__gl_prefer_renderers("gl,sw")
ui.pausebehavior(0)
ui.interact(suppress_underlay=True, suppress_overlay=True)
# If GL is able to render FRAMES frames at FPS fps in less
# than DELAY seconds, we consider it to be operational, and
# continue in GL mode. Otherwise, we rever to software
# rendering mode.
FRAMES = 5
FPS = 15
DELAY = 1
renpy.transition(Dissolve(DELAY), always=True, force=True)
ui.add(__GLTest(FRAMES, FPS, DELAY))
result = ui.interact(suppress_overlay=True, suppress_underlay=True)
if result:
__gl_prefer_renderers("gl,sw")
else:
__gl_prefer_renderers("sw")
# Init-time code:
# Make a guess as to what modes we should be in.
if persistent._gl_test is None:
persistent._gl_test = "auto"
if persistent._gl_test == "sw":
renpy.display.prefer_renderers = "sw"
label _gl_test:
# Show the test image.
scene
show expression config.gl_test_image
$ __gl_test()
# Hide the test image.
scene
return
+82 -1
View File
@@ -56,6 +56,21 @@ init -1105 python hide:
joystick_preferences=layout.classic_joystick_preferences,
)
if renpy.has_screen("main_menu"):
defaults["main_menu"] = layout.screen_main_menu
if renpy.has_screen("load") and renpy.has_screen("save"):
defaults["load_save"] = layout.screen_load_save
if renpy.has_screen("yesno_prompt"):
defaults["yesno_prompt"] = layout.screen_yesno_prompt
if renpy.has_screen("preferences"):
defaults["preferences"] = layout.screen_preferences
if renpy.has_screen("joystick_preferences"):
defaults["joystick_preferences"] = layout.screen_joystick_preferences
for k, v in defaults.iteritems():
if k not in layout.provided:
v()
@@ -343,11 +358,77 @@ init -1105 python hide:
config.load_save_selected_idle[variant] = selected_idle
config.load_save_selected_hover[variant] = selected_hover
config.load_save_hotspots[variant] = hotspots
@layout
def screen_main_menu():
renpy.load_module("_layout/screen_main_menu")
@layout
def screen_load_save():
renpy.load_module("_layout/screen_load_save")
@layout
def screen_preferences():
renpy.load_module("_layout/screen_preferences")
@layout
def screen_joystick_preferences():
renpy.load_module("_layout/screen_joystick_preferences")
@layout
def screen_yesno_prompt():
renpy.load_module("_layout/screen_yesno_prompt")
layout.ARE_YOU_SURE = u"Are you sure?"
layout.DELETE_SAVE = u"Are you sure you want to delete this save?"
layout.OVERWRITE_SAVE = u"Are you sure you want to overwrite your save?"
layout.LOADING = u"Loading will lose unsaved progress.\nAre you sure you want to do this?"
layout.QUIT = u"Are you sure you want to quit?"
layout.MAIN_MENU = u"Are you sure you want to return to the main menu?\nThis will lose unsaved progress."
@layout
def yesno_screen(message, yes=None, no=None):
"""
:doc: other
This causes the a yes/no prompt screen with the given message
to be displayed. The screen will be hidden when the user hits
yes or no.
`message`
The message that will be displayed.
`yes`
An action that is run when the user chooses yes.
`no`
An action that is run when the user chooses no.
"""
if renpy.has_screen("yesno_prompt"):
yes_action = [ Hide("yesno_prompt") ]
no_action = [ Hide("yesno_prompt") ]
if yes is not None:
yes_action.append(yes)
if no is not None:
no_action.append(no)
renpy.show_screen(
"yesno_prompt",
message=message,
yes_action=yes_action,
no_action=no_action)
renpy.restart_interaction()
return
if renpy.invoke_in_new_context(layout.yesno_prompt, None, message):
if yes is not None:
yes()
else:
if no is not None:
no()
+86 -27
View File
@@ -47,6 +47,12 @@ init -1180 python:
# preference when the game is first run.
config.default_text_cps = None
# If not None, the default value of afm_time
config.default_afm_time = None
# If not None, the default value of afm_enable
config.default_afm_enable = None
# Should we automatically define images?
config.automatic_images = None
@@ -58,6 +64,9 @@ init -1180 python:
# Layers to clear when entering the menus.
config.menu_clear_layers = [ ]
# Should we start the game with scene black or just scene?
config.start_scene_black = False
# This is updated to give the user an idea of where a save is
# taking place.
@@ -81,8 +90,20 @@ init -1180 python:
def _default_empty_window():
store.narrator("", interact=False)
who = _last_say_who
if who is not None:
who = eval(who)
if who is None:
who = narrator
if isinstance(who, NVLCharacter):
nvl_show_core()
else:
store.narrator("", interact=False)
config.empty_window = _default_empty_window
style.skip_indicator = Style(style.default, heavy=True, help='The skip indicator.')
@@ -130,27 +151,28 @@ init -1180 python:
config.help = None
def _help():
if not config.help:
def _help(help=None):
if help is None:
help = config.help
if help is None:
return
if renpy.has_label(config.help):
renpy.call_in_new_context(config.help)
if renpy.has_label(help):
renpy.call_in_new_context(help)
return
_preferences.fullscreen = False
try:
import webbrowser
webbrowser.open_new("file:///" + config.basedir + "/" + config.help)
webbrowser.open_new("file:///" + config.basedir + "/" + help)
except:
pass
init -1180 python hide:
# Called to make a screenshot happen.
def screenshot():
def _screenshot():
import os.path
import os
import __main__
@@ -181,17 +203,28 @@ init -1180 python hide:
except:
import traceback
traceback.print_exc()
init -1180 python hide:
def dump_styles():
if config.developer:
renpy.style.write_text("styles.txt")
# This is run when entering the game menu.
config.game_menu_action = None
def invoke_game_menu():
if renpy.context()._menu:
renpy.jump("_noisy_return")
if renpy.context()._main_menu:
return
else:
renpy.jump("_noisy_return")
else:
renpy.call_in_new_context('_game_menu')
if config.game_menu_action:
renpy.display.behavior.run(config.game_menu_action)
else:
renpy.call_in_new_context('_game_menu')
def keymap_toggle_skipping():
if renpy.context()._menu:
@@ -223,7 +256,7 @@ init -1180 python hide:
# the launcher.
km = renpy.Keymap(
rollback = renpy.rollback,
screenshot = screenshot,
screenshot = _screenshot,
toggle_fullscreen = renpy.toggle_fullscreen,
toggle_music = renpy.toggle_music,
toggle_skip = keymap_toggle_skipping,
@@ -391,6 +424,17 @@ init 1180 python:
if config.default_text_cps is not None:
_preferences.text_cps = config.default_text_cps
if config.default_afm_time is not None:
_preferences.afm_time = config.default_afm_time
if config.default_afm_enable is not None:
_preferences.afm_enable = config.default_afm_enable
_preferences.using_afm_enable = True
else:
_preferences.afm_enable = True
_preferences.using_afm_enable = False
if config.developer:
def _inspector(l):
@@ -402,7 +446,6 @@ init 1180 python:
ui.text("Style Inspector")
ui.text("")
if not l:
ui.text("Nothing to inspect.")
@@ -538,7 +581,7 @@ label _enter_menu:
renpy.context()._menu = True
# This may be changed, if we are already in the main menu.
renpy.context().main_menu = False
renpy.context()._main_menu = False
renpy.context_dynamic("main_menu")
renpy.context_dynamic("_window_subtitle")
renpy.context_dynamic("_window")
@@ -578,9 +621,14 @@ label _game_menu(_game_menu_screen=_game_menu_screen):
$ renpy.play(config.enter_sound)
call _enter_game_menu from _call__enter_game_menu_0
if renpy.has_label("game_menu"):
jump expression "game_menu"
if renpy.has_screen(_game_menu_screen):
$ renpy.show_screen(_game_menu_screen)
$ ui.interact()
jump _noisy_return
jump expression _game_menu_screen
@@ -622,7 +670,7 @@ label _noisy_return:
# Return to the game.
label _return:
if renpy.context().main_menu:
if renpy.context()._main_menu:
$ renpy.transition(config.game_main_transition)
jump _main_menu_screen
@@ -631,7 +679,6 @@ label _return:
return
label _confirm_quit:
call _enter_menu from _call__enter_menu_3
if renpy.has_label("confirm_quit"):
jump expression "confirm_quit"
@@ -657,6 +704,7 @@ init -1180 python hide:
# after_load.
label _after_load:
$ renpy.context()._menu = False
$ renpy.context()._main_menu = False
if config.after_load_transition:
$ renpy.transition(config.after_load_transition, force=True)
@@ -673,17 +721,25 @@ label _start:
python hide:
renpy.context()._menu = False
renpy.context()._main_menu = False
for i in config.start_callbacks:
i()
$ renpy.block_rollback()
call _gl_test
call _load_reload_game from _call__load_reload_game_1
if not _restart and config.auto_load and renpy.can_load(config.auto_load):
$ renpy.load(config.auto_load)
scene black
if config.start_scene_black:
scene black
else:
scene
if not _restart:
$ ui.pausebehavior(0)
$ ui.interact(suppress_underlay=True, suppress_overlay=True)
@@ -707,7 +763,10 @@ label _start:
$ renpy.music.stop()
# Clean out any residual scene from the splashscreen.
scene black
if config.start_scene_black:
scene black
else:
scene
# This has to be python, to deal with a case where _restart may
@@ -742,7 +801,7 @@ label _main_menu(_main_menu_screen="_main_menu_screen"):
renpy.dynamic("_load_prompt")
_load_prompt = False
renpy.context().main_menu = True
renpy.context()._main_menu = True
store.main_menu = True
jump expression _main_menu_screen
@@ -756,11 +815,11 @@ label _main_menu_screen:
jump expression "main_menu"
# New name.
if renpy.has_label("main_menu_screen"):
elif renpy.has_label("main_menu_screen"):
jump expression "main_menu_screen"
# Compatibility name.
if renpy.has_label("_library_main_menu"):
elif renpy.has_label("_library_main_menu"):
jump expression "_library_main_menu"
return
+1 -1
View File
@@ -21,7 +21,7 @@ init -1130 python hide:
for i in xrange(0, 8):
renpy.music.register_channel(i)
renpy.music.register_channel("movie", "music", False, stop_on_mute=False)
renpy.music.register_channel("movie", "music", False, stop_on_mute=False, buffer_queue=False)
# Set up default names for some of the channels.
renpy.music.alias_channel(0, "sound")
+92 -45
View File
@@ -79,8 +79,47 @@ init -1100 python:
return s[nvl_variant]
else:
return s
def nvl_show_core():
def nvl_show_screen(screen_name, **scope):
"""
Shows an nvl-mode screen. Returns the "who" widget.
"""
widget_properties = { }
dialogue = [ ]
for i, entry in enumerate(nvl_list):
if not entry:
continue
who, what, kwargs = entry
if i == len(nvl_list) - 1:
who_id = "who"
what_id = "what"
window_id = "window"
else:
who_id = "who%d" % i
what_id = "what%d" % i
window_id = "window%d" % i
widget_properties[who_id] = kwargs["who_args"]
widget_properties[what_id] = kwargs["what_args"]
widget_properties[window_id] = kwargs["window_args"]
dialogue.append((who, what, who_id, what_id, window_id))
renpy.show_screen(screen_name, _transient=True, _widget_properties=widget_properties, dialogue=dialogue, **scope)
renpy.shown_window()
return renpy.get_widget(screen_name, "what")
def nvl_show_core(who=None, what=None):
# Screen version.
if renpy.has_screen("nvl"):
return nvl_show_screen("nvl")
if renpy.in_rollback():
nvl_window = __s(style.nvl_window)['rollback']
@@ -194,16 +233,19 @@ init -1100 python:
else:
checkpoint = True
renpy.display_say(nvl_show_core,
checkpoint=checkpoint,
**display_args)
renpy.display_say(
who,
what,
nvl_show_core,
checkpoint=checkpoint,
**display_args)
def do_done(self, who, what):
if self.clear:
nvl_clear()
def do_extend(self):
renpy.mode(self.mode)
store.nvl_list = store.nvl_list[:-1]
# The default NVLCharacter.
@@ -213,6 +255,7 @@ init -1100 python:
what_style='nvl_dialogue',
window_style='nvl_entry',
type='nvl',
mode='nvl',
clear=False,
kind=adv)
@@ -224,32 +267,42 @@ init -1100 python:
def nvl_menu(items):
renpy.mode('nvl_menu')
if nvl_list is None:
store.nvl_list = [ ]
ui.layer("transient")
ui.clear()
ui.close()
ui.window(style=__s(style.nvl_window))
ui.vbox(style=__s(style.nvl_vbox))
if renpy.has_screen("nvl_choice"):
for i in nvl_list:
if not i:
continue
# Screen version.
nvl_show_screen("nvl_choice", items=items)
who, what, kw = i
rv = renpy.show_display_say(who, what, **kw)
else:
renpy.display_menu(items, interact=False,
window_style=__s(style.nvl_menu_window),
choice_style=__s(style.nvl_menu_choice),
choice_chosen_style=__s(style.nvl_menu_choice_chosen),
choice_button_style=__s(style.nvl_menu_choice_button),
choice_chosen_button_style=__s(style.nvl_menu_choice_chosen_button),
)
# Traditional version.
ui.layer("transient")
ui.clear()
ui.close()
ui.close()
ui.window(style=__s(style.nvl_window))
ui.vbox(style=__s(style.nvl_vbox))
for i in nvl_list:
if not i:
continue
who, what, kw = i
rv = renpy.show_display_say(who, what, **kw)
renpy.display_menu(items, interact=False,
window_style=__s(style.nvl_menu_window),
choice_style=__s(style.nvl_menu_choice),
choice_chosen_style=__s(style.nvl_menu_choice_chosen),
choice_button_style=__s(style.nvl_menu_choice_button),
choice_chosen_button_style=__s(style.nvl_menu_choice_chosen_button),
)
ui.close()
roll_forward = renpy.roll_forward_info()
@@ -263,29 +316,23 @@ init -1100 python:
config.nvl_adv_transition = None
config.adv_nvl_transition = None
init 1140 python:
if config.nvl_adv_transition or config.adv_nvl_transition:
# This is used to execute the nvl and adv mode transitions.
def _nvl_adv_callback(mode, old_modes):
def _nvl_adv_callback(event, interact, type, **kwargs):
if event != "begin" or not interact or renpy.get_transition():
return
old_type = renpy.last_interact_type()
if old_type == "say" and type == "nvl":
# We have an extra line in the nvl_list as we do this. So
# take it out for the duration of the nvl_show.
old_nvl_list = store.nvl_list
store.nvl_list = old_nvl_list[:-1]
nvl_show(config.adv_nvl_transition)
store.nvl_list = old_nvl_list
elif old_type == "nvl" and type == "say":
nvl_hide(config.nvl_adv_transition)
config.all_character_callbacks.insert(0, _nvl_adv_callback)
old = old_modes[0]
if config.adv_nvl_transition:
if mode == "nvl" or mode == "nvl_menu":
if old == "say" or old == "menu":
nvl_show(config.adv_nvl_transition)
if config.nvl_adv_transition:
if mode == "say" or mode == "menu":
if old == "nvl" or old == "nvl_menu":
nvl_hide(config.nvl_adv_transition)
config.mode_callbacks.append(_nvl_adv_callback)
python early hide:
+1444
View File
File diff suppressed because it is too large Load Diff
+116 -16
View File
@@ -125,7 +125,7 @@ python early hide:
if p["channel"] is not None:
channel = eval(p["channel"])
else:
channel = 7
channel = "music"
renpy.music.play(eval(p["file"]),
fadeout=eval(p["fadeout"]),
@@ -137,19 +137,24 @@ python early hide:
def predict_play_music(p):
return [ ]
def lint_play_music(p):
def lint_play_music(p, channel="music"):
file = _try_eval(p["file"], 'filename')
if p["channel"] is not None:
_try_eval(p["channel"], 'channel')
if p["channel"] is not None:
channel = _try_eval(p["channel"], 'channel')
if not isinstance(file, list):
file = [ file ]
for fn in file:
if isinstance(fn, basestring) and not renpy.loadable(fn):
renpy.error("%r is not loadable" % fn)
if isinstance(fn, basestring):
try:
if not renpy.music.playable(fn, channel):
renpy.error("%r is not loadable" % fn)
except:
pass
renpy.statements.register('play music',
parse=parse_play_music,
execute=execute_play_music,
@@ -191,7 +196,7 @@ python early hide:
if p["channel"] is not None:
channel = eval(p["channel"])
else:
channel = 7
channel = "music"
renpy.music.queue(
eval(p["file"]),
@@ -229,7 +234,7 @@ python early hide:
if p["channel"] is not None:
channel = eval(p["channel"])
else:
channel = 7
channel = "music"
renpy.music.stop(fadeout=eval(p["fadeout"]), channel=channel)
@@ -246,7 +251,7 @@ python early hide:
if p["channel"] is not None:
channel = eval(p["channel"])
else:
channel = 0
channel = "sound"
fadeout = eval(p["fadeout"]) or 0
@@ -254,17 +259,20 @@ python early hide:
fadeout=fadeout,
fadein=eval(p["fadein"]),
channel=channel)
def lint_play_sound(p, lint_play_music=lint_play_music):
return lint_play_music(p, channel="sound")
renpy.statements.register('play sound',
parse=parse_play_music,
execute=execute_play_sound,
lint=lint_play_music)
lint=lint_play_sound)
def execute_queue_sound(p):
if p["channel"] is not None:
channel = eval(p["channel"])
else:
channel = 0
channel = "sound"
renpy.sound.queue(eval(p["file"]), channel=channel)
@@ -278,7 +286,7 @@ python early hide:
if p["channel"] is not None:
channel = eval(p["channel"])
else:
channel = 0
channel = "sound"
fadeout = eval(p["fadeout"]) or 0
@@ -334,7 +342,7 @@ python early hide:
if not renpy.music.channel_defined(channel):
renpy.error("channel %r is not defined" % channel)
lint_play_music(p)
lint_play_music(p, channel)
def lint_stop_generic(p):
channel = eval(p["channel"])
@@ -439,7 +447,6 @@ python early hide:
parse=parse_pause,
lint=lint_pause,
execute=execute_pause)
init -1200 python:
@@ -453,3 +460,96 @@ init -1200 python:
except:
renpy.error('unable to evaluate %s %r' % (what, e))
##############################################################################
# Screen-related statements.
python early hide:
def parse_show_call_screen(l):
# Parse a name.
name = l.require(l.name)
# Parse a parameter list. (name -> expression string)
parameters = { }
if l.match(r"\("):
while True:
pname = l.name()
if not pname:
break
l.require(r"=")
expr = l.delimited_python(",)")
if not expr:
l.error("expected expression.")
parameters[pname] = expr
if not l.match(r','):
break
l.require(r'\)')
l.expect_eol()
return dict(name=name, parameters=parameters)
def parse_hide_screen(l):
name = l.require(l.name)
l.expect_eol()
return dict(name=name)
def execute_show_screen(p):
name = p["name"]
parameters = p["parameters"]
kwargs = { }
for k, v in parameters.iteritems():
kwargs[k] = eval(v)
renpy.show_screen(name, **kwargs)
def execute_call_screen(p):
name = p["name"]
parameters = p["parameters"]
kwargs = { }
for k, v in parameters.iteritems():
kwargs[k] = eval(v)
store._return = renpy.call_screen(name, **kwargs)
def execute_hide_screen(p):
name = p["name"]
renpy.hide_screen(name)
def lint_screen(p):
name = p["name"]
if not renpy.has_screen(name):
renpy.error("Screen %s does not exist." % name)
renpy.statements.register("show screen",
parse=parse_show_call_screen,
execute=execute_show_screen,
lint=lint_screen)
renpy.statements.register("call screen",
parse=parse_show_call_screen,
execute=execute_call_screen,
lint=lint_screen)
renpy.statements.register("hide screen",
parse=parse_hide_screen,
execute=execute_hide_screen)
+18 -13
View File
@@ -22,10 +22,14 @@ init -1200 python hide:
# Style Declarations #################################################
style.default = Style(None, help='root of style hierarchy')
style.text = Style(style.default, help='style of text')
style.fixed = Style(style.default, help='fixed layouts')
style.hbox = Style(style.default, help='horizontal boxes')
style.vbox = Style(style.default, help='vertical boxes')
style.grid = Style(style.default, help='grid layouts')
style.side = Style(style.default, help='side layouts')
style.window = Style(style.default, help='windows created with ui.window')
style.image_placement = Style(style.default, help='default placement of images on the screen')
@@ -50,7 +54,8 @@ init -1200 python hide:
style.menu_choice_chosen_button = Style(style.menu_choice_button, help='buttons containing chosen in-game menu choices')
style.menu_window = Style(style.window, help='a window containing a menu')
style.input_text = Style(style.default, help='text of an input box')
style.input = Style(style.default, help='style of an input control')
style.input_text = Style(style.input, help='text of an input box')
style.input_prompt = Style(style.default, help='prompt of an input box')
style.input_window = Style(style.window, help='window of an input box')
@@ -58,8 +63,10 @@ init -1200 python hide:
style.centered_text = Style(style.default, help='centered text')
style.imagemap = Style(style.image_placement, help='default style of imagemaps')
style.imagemap_button = Style(style.default, help='default style of buttons inside imagemaps')
style.hotspot = Style(style.default, help='default style of hotspots inside imagemaps')
style.hotbar = Style(style.default, help='default style of hotbars inside imagemaps')
style.imagemap_button = style.hotspot
style.image_button = Style(style.default, help='default style of image buttons')
style.image_button_image = Style(style.default, help='default style of images inside image buttons')
@@ -76,6 +83,8 @@ init -1200 python hide:
style.list_spacer = Style(style.default)
style.list_text = Style(style.default)
style.tile = Style(style.default, help='default style of tile')
# The base styles that can be customized by themes.
style.frame = Style(style.default, help='base style for frames.')
@@ -213,16 +222,9 @@ init -1090 python:
style.window.xfill = True
style.window.yfill = False
style.window.yminimum = 150 # Includes margins and padding.
style.window.xalign = 0.5
style.window.yalign = 1.0
# Image placement.
style.image_placement.xpos = 0.5
style.image_placement.ypos = 1.0
style.image_placement.xanchor = 0.5
style.image_placement.yanchor = 1.0
# Dialogue
style.say_label.bold = True
style.say_vbox.spacing = 8
@@ -238,7 +240,7 @@ init -1090 python:
# Menus.
style.menu_choice.idle_color = "#0ff"
style.menu_choice.hover_color = "#ff0"
style.input_text.color = "#ff0"
style.input.color = "#ff0"
# Styles used by centered.
style.centered_window.xalign = 0.5
@@ -295,7 +297,10 @@ init -1090 python:
style.list_text.color = "#000"
style.list_text.size = 14
style.list_spacer.xminimum = 15
# Tile
style.tile.clipping = True
######################################################################
+2 -6
View File
@@ -275,7 +275,7 @@ init -1110 python hide:
style.vscrollbar.hover_left_bar = img("rrvscrollbar", widget_hover, 0, 12)
style.vscrollbar.hover_right_bar = img("rrvscrollbar", widget_hover, 0, 12)
style.vscrollbar.hover_thumb = img("rrvscrollbar_thumb", widget_hover, None, None)
@theme
def roundrect(
widget = (0, 60, 120, 255),
@@ -286,10 +286,7 @@ init -1110 python hide:
disabled_text = (200, 200, 200, 255),
label = (255, 255, 255, 255),
frame = (100, 150, 200, 255),
window = (0, 0, 0, 192),
mm_root = Solid((220, 235, 255, 255)),
gm_root = Solid((220, 235, 255, 255)),
text_size=None,
small_text_size=None,
less_rounded = False,
@@ -299,7 +296,6 @@ init -1110 python hide:
button_menu = None,
rounded_window = True,
outline_bars = False,
mm_root = None,
gm_root = None):
+4 -4
View File
@@ -51,7 +51,7 @@ init -1120:
# Call this to replay the last bit of voice.
def voice_replay():
renpy.sound.play(_last_voice_play, channel=2)
renpy.sound.play(_last_voice_play, channel="voice")
# Returns true if we can replay the voice.
def voice_can_replay():
@@ -70,10 +70,10 @@ init -1120:
return
if _voice.play and not config.skipping:
renpy.sound.play(_voice.play, channel=2)
renpy.sound.play(_voice.play, channel="voice")
store._last_voice_play = _voice.play
elif not _voice.sustain:
renpy.sound.stop(channel=2)
renpy.sound.stop(channel="voice")
store._last_voice_play = _voice.play
_voice.play = None
@@ -83,7 +83,7 @@ init -1120:
config.say_sustain_callbacks.append(voice_sustain)
def voice_afm_callback():
return not renpy.sound.is_playing(channel=2)
return not renpy.sound.is_playing(channel="voice")
config.afm_callback = voice_afm_callback
+58 -26
View File
@@ -1,30 +1,34 @@
# This file contains code that helps support the development of Ren'Py
# games.
# This file contains the developer screen, which contains tools that might
# be of interest to people making Ren'Py games.
screen _developer:
window style "gm_root"
frame:
style_group "_developer"
align (.025, .05)
has vbox:
first_spacing 10
label "Developer Menu"
textbutton _(u"Return") action Return()
textbutton _(u"Reload Game (Shift + R)") action ui.callsinnewcontext("_save_reload_game")
textbutton _(u"Variable Viewer") action Jump("_debugger_screen")
textbutton _(u"Theme Test") action Jump("_theme_test")
textbutton _(u"Style Hierarchy") action Jump("_style_hierarchy")
textbutton _(u"Image Location Picker") action Jump("_image_location_picker")
textbutton _(u"Filename List") action Jump("_filename_list")
init python hide:
style._developer_button = Style(style.button)
style._developer_button.size_group = "_developer"
label _developer_screen:
python hide:
ui.window(style=style.gm_root)
ui.null()
ui.frame(xpos=10, ypos=10, style=style.menu_frame)
ui.vbox(box_first_spacing=10)
layout.label(u"Developer Menu", None)
sg = "developer_menu"
layout.button(u"Return", None, clicked=ui.returns(True), size_group=sg)
layout.button(u"Reload Game (Shift+R)", None, clicked=ui.callsinnewcontext("_save_reload_game"), size_group=sg)
layout.button(u"Variable Viewer", None, clicked=ui.jumps("_debugger_screen"), size_group=sg)
layout.button(u"Theme Test", None, clicked=ui.jumps("_theme_test"), size_group=sg)
layout.button(u"Style Hierarchy", None, clicked=ui.jumps("_style_hierarchy"), size_group=sg)
layout.button(u"FPS Meter", None, clicked=ui.jumps("_fps_meter"), size_group=sg)
layout.button(u"Image Location Picker", None, clicked=ui.jumps("_image_location_picker"), size_group=sg)
ui.close()
ui.interact()
call screen _developer
return
@@ -93,7 +97,7 @@ label _theme_test:
return ""
toggle_var = True
adj = ui.adjustment(100, 25, page=25)
adj = ui.adjustment(100, 25, page=25, adjustable=True)
while True:
@@ -370,8 +374,8 @@ init python:
sr = renpy.render(Solid("#0ff4"), w, h, st, at)
rv.blit(sr, (minx, miny))
text.append("Imagemap rectangle: %r" % ((minx, miny, maxx, maxy),))
text.append("Cropping rectangle: %r" % ((minx, miny, w, h),))
# text.append("Imagemap rectangle: %r" % ((minx, miny, maxx, maxy),))
text.append("Rectangle: %r" % ((minx, miny, w, h),))
if self.mouse:
mx, my = self.mouse
@@ -466,4 +470,32 @@ label _image_location_picker:
# ...
renpy.jump("_image_location_picker")
label _filename_list:
python hide:
import os
f = file("files.txt", "w")
for dirname, dirs, files in os.walk(config.gamedir):
dirs.sort()
files.sort()
for fn in files:
fn = os.path.join(dirname, fn)
fn = fn[len(config.gamedir) + 1:]
print >>f, fn
print fn
f.close()
renpy.launch_editor(["files.txt"], transient=1)
jump _developer_screen
init python:
config.underlay.append(im.Tile("_transparent_tile.png"))
+5 -2
View File
@@ -188,8 +188,11 @@ init python:
else:
base += 1
return base + int((int(filename) - 1) / per_page)
try:
return base + int((int(filename) - 1) / per_page)
except:
return base
# Processes a screenshot.
def _file_picker_process_screenshot(s):
return s
@@ -133,7 +133,7 @@ init python:
a channel.
"""
def __init__(self, name, mixer, enable='True', sound='None', channel=0):
def __init__(self, name, mixer, enable='True', sound='None', channel="sound"):
"""
@param name: The name of this preference, as shown to the user.
@@ -360,15 +360,18 @@ init python hide:
_VolumePreference(u"Music Volume",
'music',
'config.has_music')
_VolumePreference(u"Sound Volume",
'sfx',
'config.has_sound',
'config.sample_sound')
'config.sample_sound',
'sound')
_VolumePreference(u'Voice Volume',
'voice',
'config.has_voice',
'config.sample_voice',
2)
'voice')
_JumpPreference(u'Joystick...',
'joystick_preferences_screen',
+5 -2
View File
@@ -151,8 +151,11 @@ init python:
else:
base += 1
return base + int((int(filename) - 1) / per_page)
try:
return base + int((int(filename) - 1) / per_page)
except:
return base
# Processes a screenshot.
def _file_picker_process_screenshot(s):
return s
+9 -6
View File
@@ -77,12 +77,12 @@ init python:
ime.button("Joystick", ui.jumps("joystick_preferences_screen"), False)
def play_sound():
renpy.sound.play(config.sample_sound)
renpy.music.play(config.sample_sound, channel="sound")
ime.button("Sound Test", play_sound, False)
def play_voice():
renpy.sound.play(config.sample_sound, channel=2)
renpy.music.play(config.sample_sound, channel="voice")
ime.button("Voice Test", play_voice, False)
@@ -124,11 +124,14 @@ init python:
_preferences.set_volume('sfx', v / 128.0)
def set_voice(v):
_preferences.set_volume('voice', v / 128.0)
ime.bar("Music Volume", 128, int(_preferences.get_volume('music') * 128), set_music)
ime.bar("Sound Volume", 128, int(_preferences.get_volume('sfx') * 128), set_sound)
ime.bar("Voice Volume", 128, int(_preferences.get_volume('voice') * 128), set_voice)
if config.has_music:
ime.bar("Music Volume", 128, int(_preferences.get_volume('music') * 128), set_music)
if config.has_sound:
ime.bar("Sound Volume", 128, int(_preferences.get_volume('sfx') * 128), set_sound)
if config.has_voice:
ime.bar("Voice Volume", 128, int(_preferences.get_volume('voice') * 128), set_voice)
ime.close()
ui.interact(mouse="gamemenu")
@@ -0,0 +1,16 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
# See LICENSE.txt for license details.
init python:
layout.provides('joystick_preferences')
label joystick_preferences_screen:
$ renpy.show_screen('joystick_preferences')
$ ui.interact()
jump _noisy_return
+19
View File
@@ -0,0 +1,19 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
# See LICENSE.txt for license details.
init python:
layout.provides('load_save')
label load_screen:
$ renpy.show_screen('load')
$ ui.interact()
jump _noisy_return
label save_screen:
$ renpy.show_screen('save')
$ ui.interact()
jump _noisy_return
+14
View File
@@ -0,0 +1,14 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
# See LICENSE.txt for license details.
init python:
layout.provides('main_menu')
label main_menu_screen:
$ renpy.show_screen("main_menu")
$ ui.interact()
return
+16
View File
@@ -0,0 +1,16 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
# See LICENSE.txt for license details.
init python:
layout.provides('preferences')
label preferences_screen:
$ renpy.show_screen('preferences')
$ ui.interact()
jump _noisy_return
+11
View File
@@ -0,0 +1,11 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
# See LICENSE.txt for license details.
init python hide:
layout.provides('yesno_prompt')
def yesno_prompt(screen, message):
return renpy.call_screen('yesno_prompt', message=message, yes_action=Return(True), no_action=Return(False))
layout.yesno_prompt = yesno_prompt
Binary file not shown.

After

Width:  |  Height:  |  Size: 436 B

-1
View File
@@ -1 +0,0 @@
dist/console.exe
+50 -32
View File
@@ -9,6 +9,9 @@ import time
import zlib
import compileall
import shutil
import subprocess
import makeupdate
import time
zlib.Z_DEFAULT_COMPRESSION = 9
@@ -20,7 +23,7 @@ def data(fn):
if fn.startswith("renpy.app"):
return rv
if fn.endswith(".rpy") or fn.endswith(".py") or fn.endswith(".txt"):
if fn.endswith(".rpy") or fn.endswith(".rpym") or fn.endswith(".py") or fn.endswith(".txt"):
rv = rv.replace("\n", "\r\n")
rv = rv.replace("\r\r\n", "\r\n")
@@ -87,7 +90,11 @@ def tree(root):
if ".svn" in dirs:
dirs.remove(".svn")
if ".doctrees" in dirs:
dirs.remove(".doctrees")
for f in filenames:
if f[-1] == '~' or f[0] == '.':
continue
@@ -113,41 +120,44 @@ def main():
prefix = sys.argv[1]
# Update the update-version.txt file.
p = subprocess.Popen(["bzr", "revno"], stdout=subprocess.PIPE)
revno = p.stdout.read().strip() + "-" + str(time.time())
p.wait()
f = file("lib/update-version.txt", "w")
f.write(revno + " base\n")
f.close()
# Compile all the python files.
compileall.compile_dir("renpy/", ddir=prefix + "/renpy/", force=1)
os.environ['RENPY_PATH_ELIDE'] = '/home/tom/ab/renpy:' + prefix
# Chmod the mac app.
os.chmod("./renpy.app/Contents/MacOS/Ren'Py Launcher", 0755)
# Chmod down renpy.py, for now.
os.chmod("renpy.py", 0644)
# Compile the various games
for i in [ 'tutorial/game', 'launcher', 'template/game', 'the_question/game' ]:
os.system("./renpy.sh --compile --game " + i)
files = [ ]
more_files = [ ]
files.append("CHANGELOG.txt")
files.append("LICENSE.txt")
files.extend(tree("common"))
more_files.append("console.exe")
files.extend(tree("launcher"))
files.extend(tree("tutorial"))
# files.extend(tree("dse"))
files.extend(tree("the_question"))
# editor = tree("editor")
# editor.remove("editor/scite.exe")
# files.append("editor/scite.exe")
# more_files.extend(editor)
more_files.extend(tree("jedit"))
# files.extend(tree("extras"))
more_files.extend(tree("lib"))
more_files.extend(tree("lib/linux-x86"))
module_files = [
"lib/pysdlsound/linmixer.py",
"lib/pysdlsound/__init__.py",
@@ -175,34 +185,30 @@ def main():
"_renpybidi.c",
"renpybidicore.c",
"_renpybidi.pyx",
"_renpy_pysdlgl.c",
"_renpy_pysdlgl.pyx",
"_renpy_tegl.c",
"maketegl.py",
"maketegl.txt",
]
for i in module_files:
files.append('module/' + i)
more_files.append('python25.dll')
more_files.append('msvcr71.dll')
files.extend(tree('renpy'))
more_files.extend(tree('renpy.app'))
more_files.append('renpy.code')
more_files.append('renpy.exe')
files.append('renpy.py')
more_files.append('python26.dll')
more_files.append('msvcr90.dll')
more_files.append('Microsoft.VC90.CRT.manifest')
more_files.extend(tree('renpy.app'))
more_files.append('renpy.exe')
more_files.append("console.exe")
more_files.append('renpy.sh')
files.extend(tree('template'))
# files.extend(tree('tools'))
files.extend(tree('doc'))
files.append('doc/index.html')
files.append('doc/common.css')
files.append('doc/docs.css')
files.append('doc/monobook.css')
files.append('doc/monobook2.css')
files.append('doc/shared.css')
files.extend(tree('doc/reference'))
files.extend(tree('doc/tutorials'))
files.extend(tree('doc/images'))
files.sort()
more_files.sort()
@@ -211,7 +217,9 @@ def main():
zipup("dists/" + prefix + "-sdk.zip", prefix, files + more_files)
print "----"
tarup("dists/" + prefix + "-sdk.tar.bz2", prefix, files + more_files)
print "----"
tarup("dists/" + prefix + "-source.tar.bz2", prefix, files)
print "----"
# Make the 7zip.
os.chdir("dists")
@@ -224,13 +232,23 @@ def main():
os.system("7z a " + prefix + "-sdk.7z " + prefix)
os.system("cat ../7z.sfx " + prefix + "-sdk.7z > " + prefix + "-sdk.7z.exe""")
shutil.rmtree(prefix)
os.unlink(prefix + "-sdk.7z")
os.chdir("..")
if os.path.exists("updates/prerelease"):
shutil.rmtree("updates/prerelease")
os.rename("dists/" + prefix, "updates/prerelease")
os.unlink("updates/prerelease/lib/update-version.txt")
makeupdate.make_update("updates/prerelease", revno)
os.chmod("renpy.py", 0755)
print
print "Did you remember to rebuild the exe after the last change?"
print "Did you run me with renpython -OO?"
print "Was ming using the right crt?"
print "Did you update renpy.py and launcher/script_version.rpy?"
print "Did you run with a RENPY_SCALE_FACTOR?"
Symlink
+1
View File
@@ -0,0 +1 @@
sphinx/build/html/
-16
View File
@@ -1,16 +0,0 @@
#bodyContent {
font-size: medium;
background: #fff;
margin-left: 20%;
margin-right: 20%;
padding: 1.5em;
}
.editsection {
display: none;
}
#bodyContent a.external {
background: none;
padding-right: 0px;
}
-19
View File
@@ -1,19 +0,0 @@
#!/bin/sh
wget http://www.renpy.org/w/skins/common/shared.css -O shared.css
wget http://www.renpy.org/w/skins/monobook/main.css -O monobook.css
wget 'http://www.renpy.org/w/index.php?title=MediaWiki:Common.css&usemsgcache=yes&action=raw&ctype=text/css&smaxage=18000' -O common.css
wget 'http://www.renpy.org/w/index.php?title=MediaWiki:Monobook.css&usemsgcache=yes&action=raw&ctype=text/css&smaxage=18000' -O monobook2.css
rm -Rf www.renpy.org
wget -e robots=off -m -I /wiki/renpy/doc/reference/,/wiki/renpy/doc/tutorials/,/w/images -m http://www.renpy.org/wiki/renpy/doc/index
rm -Rf images
mkdir -p images
cp `find www.renpy.org -name \*.png -type f` images
No jpgs yet.
cp `find www.renpy.org -name \*.jpg -type f` images
rm -Rf reference tutorials
python2.5 process.py
-164
View File
@@ -1,164 +0,0 @@
#!/usr/bin/python2.4
import sys
import os.path
# import xml.etree.ElementTree as elementtree
# sys.modules['elementtree'] = elementtree
# from elementtree.ElementTree import ElementTree, Element, SubElement, tostring, fromstring
# from elementtidy import TidyHTMLTreeBuilder
from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring, fromstring
from elementtidy import TidyHTMLTreeBuilder
# Removes everyhing we don't care about from the wikipages.
def remove_crap(n):
classes = n.attrib.get("class", "").split()
if "editsection" in classes:
return None
if "printfooter" in classes:
return None
if "magnify" in classes:
return None
id = n.attrib.get("id", None)
if "catlinks" == id:
return None
newchildren = [ ]
for i in n:
i = remove_crap(i)
if i is not None:
newchildren.append(i)
n[:] = newchildren
if n.tag == "a" and not n.text:
n.text = "SPACE REMOVE ME PLEASE"
return n
def process(src, dst, nav):
if nav:
nav = fromstring(nav)
base = "../" * (len(dst.split('/')) - 1)
if dst.startswith("./"):
base = ""
# tree = TidyHTMLTreeBuilder.parse(src)
code = file(src).read()
code = code.replace("&nbsp;", u"\u00a0".encode("utf-8"))
tree = fromstring(code)
XHTML = "{http://www.w3.org/1999/xhtml}"
for elem in tree.getiterator():
if elem.tag.startswith(XHTML):
elem.tag = elem.tag[len(XHTML):]
by_id = dict()
for n in tree.getiterator():
if "id" in n.attrib:
by_id[n.attrib["id"]] = n
html = Element("html")
head = SubElement(html, "head")
title = SubElement(head, "title")
title.text = tree.findtext(".//title")
head = SubElement(head, "link", rel="stylesheet", href=base + "shared.css")
head = SubElement(head, "link", rel="stylesheet", href=base + "monobook.css")
head = SubElement(head, "link", rel="stylesheet", href=base + "common.css")
head = SubElement(head, "link", rel="stylesheet", href=base + "monobook2.css")
head = SubElement(head, "link", rel="stylesheet", href=base + "docs.css")
body = SubElement(html, "body")
# gw = SubElement(body, "div", id="globalWrapper")
# cc = SubElement(gw, "div", id="column-content")
# content = SubElement(cc, "div", id="content")
bc = by_id['bodyContent']
body.append(bc)
bc.remove(by_id['siteSub'])
bc.remove(by_id['contentSub'])
bc.remove(by_id['jump-to-nav'])
for n in bc.findall(".//a"):
if "href" in n.attrib:
href = n.attrib['href']
if href.startswith("/wiki/Image:") or href.startswith("/w/"):
n.attrib['href'] = 'http://www.renpy.org' + href
continue
if href.startswith("#"):
continue
if href.startswith("http:"):
continue
href = href.replace("/wiki/renpy/doc/", base)
if "#" in href:
href.replace("#", ".html#")
else:
href += ".html"
n.attrib['href'] = href
for n in bc.findall(".//img"):
src = n.attrib["src"]
src = base + "images" + src[src.rfind("/"):]
n.attrib["src"] = src
if nav:
hr = Element("hr")
bc[:] = [ nav ] + list(bc) + [ hr, nav ]
html = remove_crap(html)
doc = tostring(html)
doc = doc.replace("SPACE REMOVE ME PLEASE", "")
file(dst, "w").write(doc)
def process_dir(src, dst, nav):
try:
os.makedirs(dst)
except:
pass
for fn in os.listdir(src):
if os.path.isdir(src + "/" + fn):
continue
if fn.endswith(".1"):
continue
print src + "/" + fn
process(src + "/" + fn, dst + "/" + fn + ".html", nav)
nav = '<p class="docnav"><a href="../index.html">documentation index</a></p>'
process_dir("www.renpy.org/wiki/renpy/doc/tutorials", "tutorials", nav)
nav = '<p class="docnav"><a href="../index.html">documentation index</a> &#x25e6; <a href="Reference_Manual.html">reference manual</a> &#x25e6; <a href="Function_Index.html">function index</a></p>'
process_dir("www.renpy.org/wiki/renpy/doc/reference", "reference", nav)
nav = '<p class="docnav"><a href="../../index.html">documentation index</a> &#x25e6; <a href="../Reference_Manual.html">reference manual</a> &#x25e6; <a href="../Function_Index.html">function index</a></p>'
process_dir("www.renpy.org/wiki/renpy/doc/reference/functions", "reference/functions", nav)
nav = ''
process_dir("www.renpy.org/wiki/renpy/doc/", ".", nav)
+79 -93
View File
@@ -5,40 +5,7 @@
import struct
import sys
import array
# The starting point of the resource segment in the file.
RESOURCE_BASE=0x3600
# The virtual memory location the resource segment is loaded
# to.
RESOURCE_VIRTUAL=0x6000
# The offset of the field that tells us with the alignment need be.
ALIGNMENT_FIELD = 0x130
# The start of the .rsrc segment header.
RSRC_HEADER = 0x268
# Locations in the file where we need to patch in the resource
# segment length.
RESOURCE_LENGTH_PATCHES = [ 0x0184, RSRC_HEADER + 0x8 ]
# Locations in the file where we need to patch in the padded
# resource segment length.
RESOURCE_PADDED_PATCHES = [ RSRC_HEADER + 0x10 ]
# Locations in the file where we need to patch in the change in the
# size of the resource segement (and hence the change in the file's
# total size.)
SIZE_DELTA_PATCHES = [ 0x148 ]
# A location in the file that will be checked to be sure it matches
# RESOURCE_BASE.
CHECK_ADDRESS = RSRC_HEADER + 0x14
# A location in the file that will be checked to make sure it matches
# RESOURCE_VIRTUAL
CHECK_ADDRESS2 = RSRC_HEADER + 0xc
import pefile
# This class performs various operations on memory-loaded binary files,
# including modifications.
@@ -89,8 +56,7 @@ class BinFile(object):
def substring(self, start, len):
return self.a[start:start+len].tostring()
def __init__(self, fn):
data = open(fn, "rb").read()
def __init__(self, data):
self.a = array.array('B')
self.a.fromstring(data)
@@ -98,50 +64,53 @@ class BinFile(object):
# These functions parse data out of the file. In these functions, offset is
# relative to the start of the file.
# The virtual address of the resource segment.
resource_virtual = 0
# This parses a data block out of the resources.
def parse_data(offset):
pe.seek(RESOURCE_BASE + offset)
data_offset = pe.u32()
data_len = pe.u32()
code_page = pe.u32()
pe.u32()
def parse_data(bf, offset):
bf.seek(offset)
data_offset = bf.u32()
data_len = bf.u32()
code_page = bf.u32()
bf.u32()
l = [ ]
pe.seek(data_offset + RESOURCE_BASE - RESOURCE_VIRTUAL)
bf.seek(data_offset - resource_virtual)
for i in range(data_len):
l.append(chr(pe.u8()))
l.append(chr(bf.u8()))
return (code_page, "".join(l))
# This parses a resource directory.
def parse_directory(offset):
def parse_directory(bf, offset):
pe.seek(RESOURCE_BASE + offset)
char = pe.u32()
timedate = pe.u32()
major = pe.u16()
minor = pe.u16()
n_named = pe.u16()
n_id = pe.u16()
bf.seek(offset)
char = bf.u32()
timedate = bf.u32()
major = bf.u16()
minor = bf.u16()
n_named = bf.u16()
n_id = bf.u16()
entries = [ ]
for i in range(n_named + n_id):
entries.append((pe.u32(), pe.u32()))
entries.append((bf.u32(), bf.u32()))
rv = { }
for name, value in entries:
if name & 0x80000000:
pe.seek((name & 0x7fffffff) + RESOURCE_BASE)
name = pe.name()
bf.seek((name & 0x7fffffff))
name = bf.name()
if value & 0x80000000:
value = parse_directory(value & 0x7fffffff)
value = parse_directory(bf, value & 0x7fffffff)
else:
value = parse_data(value)
value = parse_data(bf, value)
rv[name] = value
@@ -182,8 +151,6 @@ class Packer(object):
self.entries_offset = len(head)
return self.pack_dict(d, 0) + self.entries + self.data
def pack_name(self, s):
rv = self.data_offset + len(self.data)
@@ -204,7 +171,7 @@ class Packer(object):
daddr = len(self.data) + self.data_offset
self.entries += struct.pack("<IIII", daddr + RESOURCE_VIRTUAL, len(data), codepage, 0)
self.entries += struct.pack("<IIII", daddr + resource_virtual, len(data), codepage, 0)
self.data += data
# if len(self.data) % 1 == 1:
@@ -212,9 +179,6 @@ class Packer(object):
return rv
def pack_dict(self, d, offset):
name_entries = sorted((a, b) for a, b in d.iteritems() if isinstance(a, unicode))
id_entries = sorted((a, b) for a, b in d.iteritems() if isinstance(a, int))
@@ -245,7 +209,7 @@ class Packer(object):
# This loads in an icon file, and returns a dictionary that is suitable for
# use in the resources of an exe file.
def load_icon(fn):
f = BinFile(fn)
f = BinFile(file(fn, "rb").read())
f.seek(0)
f.u16()
@@ -289,51 +253,73 @@ def load_icon(fn):
# This is the main function that should be called externally, that copies over
# the icons.
def change_icons(oldexe, icofn):
global pe
pe = BinFile(oldexe)
global resource_virtual
# Check that RESOURCE_BASE and RESOURCE_VIRTUAL are still valid.
pe.seek(CHECK_ADDRESS)
if pe.u32() != RESOURCE_BASE:
raise Exception("RESOURCE_BASE is no longer correct. Please check all relocations.")
pe = pefile.PE(oldexe)
pe.seek(CHECK_ADDRESS2)
if pe.u32() != RESOURCE_VIRTUAL:
raise Exception("RESOURCE_VIRTUAL is no longer correct. Please check all relocations.")
for s in pe.sections:
if s.Name == ".rsrc\0\0\0":
rsrc_section = s
break
else:
raise Exception("Couldn't find resource section.")
resources = parse_directory(0)
# show_resources(resources, "")
base = rsrc_section.PointerToRawData
resource_virtual = rsrc_section.VirtualAddress
physize = rsrc_section.SizeOfRawData
virsize = rsrc_section.Misc_VirtualSize
f = file(oldexe, "rb")
f.seek(base)
data = f.read(physize)
f.close()
bf = BinFile(data)
resources = parse_directory(bf, 0)
# show_resources(resources, "")
resources.update(load_icon(icofn))
# show_resources(resources, "")
# show_resources(resources, "")
rsrc = Packer().pack(resources)
rsrc_len = len(rsrc)
pe.seek(ALIGNMENT_FIELD)
alignment = pe.u32()
alignment = pe.OPTIONAL_HEADER.SectionAlignment
# print "Alignment is", alignment
if len(rsrc) % alignment:
pad = alignment - (len(rsrc) % alignment)
padding = "RENPYVNE" * (pad / 8 + 1)
padding = padding[:pad]
rsrc += padding
padded_len = len(rsrc)
for addr in RESOURCE_LENGTH_PATCHES:
pe.set_u32(addr, rsrc_len)
newsize = len(rsrc)
rsrc_section.Misc_VirtualSize += newsize - virsize
rsrc_section.Misc_PhysicalAddress += newsize - virsize
rsrc_section.Misc += newsize - virsize
rsrc_section.SizeOfRawData += newsize - physize
pe.OPTIONAL_HEADER.SizeOfInitializedData += newsize - physize
for addr in RESOURCE_PADDED_PATCHES:
pe.seek(addr)
size_delta = padded_len - pe.u32()
pe.set_u32(addr, padded_len)
# Resource size.
pe.OPTIONAL_HEADER.DATA_DIRECTORY[2].Size += newsize - virsize
for addr in SIZE_DELTA_PATCHES:
pe.seek(addr)
pe.set_u32(addr, pe.u32() + size_delta)
# Compute the total size of the image.
total_size = 0
for i in pe.sections:
return pe.tostring()[:RESOURCE_BASE] + rsrc
sec_size = i.Misc_VirtualSize
sec_size = sec_size - (sec_size % alignment) + alignment
print sec_size
total_size += sec_size
pe.OPTIONAL_HEADER.SizeOfImage = total_size
return pe.write()[:base] + rsrc
if __name__ == "__main__":
+536
View File
@@ -0,0 +1,536 @@
import os
import os.path
import zipfile
import tarfile
import time
import sys
import struct
import zlib
zlib.Z_DEFAULT_COMPRESSION = 9
import binascii
import change_icon
import argparse
# The directory containing the project that we'll be distributing.
project_path = None
# The path to the Ren'Py base directory.
renpy_base = None
# A function that is called to give information about what is going
# on now.
def info(title, body):
return
# A function that is called to give a progress report.
def progress(title, total, amount):
amount += 1
if amount % 25 == 0:
print title, amount, "of", total
# A translation function.
def _(s):
return s
# These are files that are ignored wherever they are found in a
# distribution.
ignored_files = (
"thumbs.db",
"traceback.txt",
"errors.txt",
"files.txt",
"saves"
)
# These are files (and directories) that are ignored when found in
# the root directory of the distribution.
root_ignored_files = (
"common",
"renpy",
"renpy.code",
"python23.dll",
"python24.dll",
"python25.dll",
"msvcr71.dll",
"lib",
"iliad-icon.png",
"manifest.xml",
"icon.ico",
"icon.icns",
"launcherinfo.py",
"archived",
)
# Extensions that should be made executable.
executable_extensions = (
"MacOS",
"so",
"dylib",
".sh",
"python",
"python.real",
)
class MyZipFile(zipfile.ZipFile):
"""
Modified ZipFile class that can insert a file into the archive,
using a supplied ZipInfo object. Code comes from the writestr
and write methods of ZipFile.
"""
def write_file_with_zipinfo(self, filename, zinfo, compress_type=None):
"""Put the bytes from filename into the archive under the name
arcname."""
st = os.stat(filename)
if compress_type is None:
zinfo.compress_type = self.compression
else:
zinfo.compress_type = compress_type
zinfo.file_size = st.st_size
zinfo.flag_bits = 0x00
zinfo.header_offset = self.fp.tell() # Start of header bytes
self._writecheck(zinfo)
self._didModify = True
fp = open(filename, "rb")
# Must overwrite CRC and sizes with correct data later
zinfo.CRC = CRC = 0
zinfo.compress_size = compress_size = 0
zinfo.file_size = file_size = 0
self.fp.write(zinfo.FileHeader())
if zinfo.compress_type == zipfile.ZIP_DEFLATED:
cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
zlib.DEFLATED, -15)
else:
cmpr = None
while 1:
buf = fp.read(1024 * 64)
if not buf:
break
file_size = file_size + len(buf)
CRC = binascii.crc32(buf, CRC)
if cmpr:
buf = cmpr.compress(buf)
compress_size = compress_size + len(buf)
self.fp.write(buf)
fp.close()
if cmpr:
buf = cmpr.flush()
compress_size = compress_size + len(buf)
self.fp.write(buf)
zinfo.compress_size = compress_size
else:
zinfo.compress_size = file_size
zinfo.CRC = CRC
zinfo.file_size = file_size
# Seek backwards and write CRC and file sizes
position = self.fp.tell() # Preserve current position in file
self.fp.seek(zinfo.header_offset + 14, 0)
self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size,
zinfo.file_size))
self.fp.seek(position, 0)
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo
def tree(
src,
dest,
exclude_suffix=[ ".pyc", "~", ".bak", ".old", ".new" ],
exclude_prefix=[ "#", "." ],
exclude_files = set(ignored_files),
root_exclude_prefix = [ ],
root_exclude_suffix = [ ".py", ".sh", ".app" ],
root_exclude_files = set(root_ignored_files),
root=False):
"""
Returns a list of source-filename, destination-filename pairs.
"""
if dest[0] != "/":
raise Exception("Destination must begin with /: %r" % dest)
src = src.rstrip('/')
dest = dest.rstrip('/')
def include(fn, is_root):
"""
Returns True if the file should be included in the list of
files we are copying.
"""
for i in exclude_suffix:
if fn.endswith(i):
return False
for i in exclude_prefix:
if fn.startswith(i):
return False
if fn in exclude_files:
return False
if not root or not is_root:
return True
for i in root_exclude_suffix:
if fn.endswith(i):
return False
for i in root_exclude_prefix:
if fn.startswith(i):
return False
if fn in root_exclude_files:
return False
return True
rv = [ ]
# Walk the tree, including what is necessary.
for srcdir, dirs, files in os.walk(src):
is_root = (srcdir == src)
srcdir += "/"
destdir = dest + srcdir[len(src):]
destdir.replace("\\", "/")
rv.append((srcdir, destdir))
for fn in files:
if not include(fn, is_root):
continue
sfn = srcdir + fn
dfn = destdir + fn
rv.append((sfn, dfn))
dirs[:] = [ i for i in dirs if include(i, is_root) ]
rv = [ (a.replace("\\", "/"), b.replace("\\", "/")) for a, b in rv ]
return rv
def make_zip(t, filename, files, file_data):
"""
This creates `filename`.zip, containing `files`, placed in the
`filename` directory. `file_data` is a map from source file to
replacement data.
"""
files.sort(key=lambda a : a[1])
progress_len = len(files)
fn = os.path.join(os.path.dirname(project_path), filename)
zf = MyZipFile(fn + ".zip", "w", zipfile.ZIP_DEFLATED)
for i, (fn, an) in enumerate(files):
progress(t, progress_len, i)
if os.path.isdir(fn):
continue
zi = zipfile.ZipInfo(filename + an)
s = os.stat(fn)
zi.date_time = time.gmtime(s.st_mtime)[:6]
zi.compress_type = zipfile.ZIP_DEFLATED
zi.create_system = 3
for i in executable_extensions:
if os.path.dirname(fn).endswith(i) or fn.endswith(i):
zi.external_attr = long(0100777) << 16
break
else:
zi.external_attr = long(0100666) << 16
if fn in file_data:
data = file_data[fn]
zf.writestr(zi, data)
else:
zf.write_file_with_zipinfo(fn, zi)
zf.close()
def make_tar(t, filename, files):
"""
Makes a tarfile, as above.
"""
files.sort(key=lambda a : a[1])
progress_len = len(files)
fn = os.path.join(os.path.dirname(project_path), filename)
tf = tarfile.open(fn + ".tar.bz2", "w:bz2")
tf.dereference = True
for j, (fn, an) in enumerate(files):
progress(t, progress_len, j)
info = tf.gettarinfo(fn, filename + an)
perms = 0666
if info.isdir():
perms = 0777
for i in executable_extensions:
if fn.endswith(i):
perms = 0777
info.mode = perms
info.uid = 1000
info.gid = 1000
info.uname = "renpy"
info.gname = "renpy"
if info.isreg():
tf.addfile(info, file(fn, "rb"))
else:
tf.addfile(info)
tf.close()
def distribute(
_project_path,
_renpy_base,
base_name,
executable_name,
ignore_extensions,
documentation_extensions,
build_windows,
build_linux,
build_mac,
build_all):
global project_path
global renpy_base
project_path = _project_path
renpy_base = _renpy_base
base_name = base_name.encode("utf-8")
executable_name = executable_name.encode("utf-8")
ignore_extensions = ignore_extensions.encode("utf-8")
documentation_extensions = documentation_extensions.encode("utf-8")
# Convert some of these to more useful formats.
ignore_extensions = [ i.strip() for i in ignore_extensions.split() ]
documentation_extensions = [ i.strip() for i in documentation_extensions.split() ]
# Scan for the files we want to include in the various distributions.
info(_(u"Scanning..."), "")
# Files included in the various distributions.
multi_files = [ ]
win_files = [ ]
linux_files = [ ]
mac_files = [ ]
# A map from source file name to replacement data to be placed in
# that file.
file_data = { }
######################################################################
# Multi files.
rb = renpy_base.replace("\\", "/") + "/"
# Project files.
multi_files.extend(tree(project_path, "/", root=True, exclude_suffix=ignore_extensions))
multi_files.append((rb + "renpy.py", "/" + executable_name + ".py"))
# Renpy files.
multi_files.extend(tree(rb + "common", "/common"))
multi_files.extend(tree(rb + "renpy", "/renpy"))
multi_files.append((rb + "LICENSE.txt", "/renpy/LICENSE.txt"))
def add_script_version(fn, ignore_extensions=ignore_extensions, multi_files=multi_files, rb=rb):
"""
Add a script_version file if it does not already exist, and if the
extension is allowed by the game.
"""
for a, b in multi_files:
if b == "/game/" + fn:
return
for i in ignore_extensions:
if fn.endswith(i):
return
multi_files.append((rb + "launcher/" + fn, "/game/" + fn))
add_script_version("script_version.rpy")
add_script_version("script_version.rpyc")
######################################################################
# Windows files.
if build_windows or build_all:
win_files.append((rb + "renpy.exe", "/" + executable_name + ".exe"))
win_files.append((rb + "python26.dll", "/python26.dll"))
win_files.append((rb + "msvcr90.dll", "/msvcr90.dll"))
win_files.append((rb + "Microsoft.VC90.CRT.manifest", "/Microsoft.VC90.CRT.manifest"))
win_files.append((rb + "lib", "/lib"))
win_files.extend(tree(rb + "lib/windows-x86", "/lib/windows-x86"))
if os.path.exists(project_path + "/icon.ico"):
file_data[rb + "renpy.exe"] = change_icon.change_icons(
rb + "renpy.exe",
project_path + "/icon.ico",
)
######################################################################
# Linux files.
if build_linux or build_all:
linux_files.append((rb + "renpy.sh", "/" + executable_name + ".sh"))
linux_files.append((rb + "lib", "/lib"))
linux_files.append((rb + "lib/python", "/lib/python"))
linux_files.extend(tree(rb + "lib/linux-x86", "/lib/linux-x86"))
# Warning: The tar.bz2 builder doesn't support file_data.
######################################################################
# Mac (non-app) files.
if build_mac or build_all:
mac_files = tree(rb + "renpy.app",
"/" + executable_name + ".app")
# Rename executable.
mac_files = [ (fn, an.replace("Ren'Py Launcher", executable_name)) for (fn, an) in mac_files ]
# Plist file.
quoted_name = executable_name.replace("&", "&amp;").replace("<", "&lt;")
info_plist = file(rb + "renpy.app/Contents/Info.plist", "rb").read().replace("Ren'Py Launcher", quoted_name)
file_data[rb + "renpy.app/Contents/Info.plist"] = info_plist
# Launcher script.
quoted_name = executable_name.replace("\"", "\\\"")
launcher_py = file(rb + "renpy.app/Contents/Resources/launcher.py", "rb").read().replace("Ren'Py Launcher", quoted_name)
file_data[rb + "renpy.app/Contents/Resources/launcher.py"] = launcher_py
# Icon file.
if os.path.exists(project_path + "/icon.icns"):
icon_data = file(project_path + "/icon.icns", "rb").read()
file_data[rb + "renpy.app/Contents/Resources/launcher.icns"] = icon_data
######################################################################
# Now, build the various distributions.
if build_windows:
make_zip(
_(u"Building Windows..."),
base_name + "-win32",
multi_files + win_files,
file_data)
if build_linux:
make_tar(
_(u"Building Linux..."),
base_name + "-linux-x86",
multi_files + linux_files)
if build_mac:
# Reorganize the files so all the non application files live inside
# the application. If there's documentation involved, then it
# lives in both places.
macapp_files = [ ]
for fn, an in multi_files + mac_files:
if not an.startswith("/" + executable_name + ".app"):
new_an = "/" + executable_name + ".app/Contents/Resources/autorun" + an
macapp_files.append((fn, new_an))
if an.rindex('/') == 0:
for i in documentation_extensions:
if fn.endswith(i):
macapp_files.append((fn, an))
break
else:
macapp_files.append((fn, an))
make_zip(
_(u"Building Macintosh..."),
base_name + "-mac",
macapp_files,
file_data)
if build_all:
make_zip(
_(u"Building Combined..."),
base_name + "-all",
multi_files + win_files + linux_files + mac_files,
file_data)
def main():
ap = argparse.ArgumentParser(description="Prepare a Ren'Py game for distribution.")
ap.add_argument("project_path", type=str, help="The path to the directory containing the project.")
ap.add_argument("base_name", type=str, help="The base name of the archive files produced.")
ap.add_argument("executable_name", type=str, help="The name of the executables produced.")
ap.add_argument("--renpy-base", type=str, default=None, help="The path to the Ren'Py distribution.")
ap.add_argument("--ignore-extensions", type=str, default="~ .bak", help="A space-separated list of extensions to ignore.")
ap.add_argument("--documentation-extensions", type=str, default="txt html", help="A space-separated list of extensions to treat as documentation.")
ap.add_argument("--build-windows", action="store_true", default=False, help="Build the Windows distribution.")
ap.add_argument("--build-mac", action="store_true", default=False, help="Build the Mac OS X distribution.")
ap.add_argument("--build-linux", action="store_true", default=False, help="Build the Windows distribution.")
ap.add_argument("--build-all", action="store_true", default=False, help="Build the All Platforms distribution.")
args = ap.parse_args()
renpy_base = args.renpy_base
if renpy_base is None:
renpy_base = os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))
distribute(
args.project_path,
renpy_base,
base_name=args.base_name,
executable_name=args.executable_name,
ignore_extensions=args.ignore_extensions,
documentation_extensions=args.documentation_extensions,
build_windows=args.build_windows,
build_mac=args.build_mac,
build_linux=args.build_linux,
build_all=args.build_all)
if __name__ == "__main__":
main()
+19 -462
View File
@@ -1,236 +1,21 @@
# This file contains the code needed to build a Ren'Py distribution.
init python:
import os
import os.path
import zipfile
import tarfile
import time
import sys
import struct
import zlib
zlib.Z_DEFAULT_COMPRESSION = 9
init 12 python:
import binascii
import pefile
# These are files that are ignored wherever they are found in a
# distribution.
ignored_files = (
"thumbs.db",
"traceback.txt",
"errors.txt",
"saves"
)
import distribute
# These are files (and directories) that are ignored when found in
# the root directory of the distribution.
root_ignored_files = (
"common",
"renpy",
"renpy.code",
"python23.dll",
"python24.dll",
"python25.dll",
"msvcr71.dll",
"lib",
"iliad-icon.png",
"manifest.xml",
"icon.ico",
"icon.icns",
"launcherinfo.py",
"archived",
)
distribute.progress = progress
distribute.info = info
distribute._ = _
# Extensions that should be made executable.
executable_extensions = (
"MacOS",
"so",
"dylib",
".sh",
"python",
"python.real",
)
def tree(
src,
dest,
exclude_suffix=[ ".pyc", "~", ".bak" ],
exclude_prefix=[ "#", "." ],
exclude_files = set(ignored_files),
root_exclude_prefix = [ ],
root_exclude_suffix = [ ".py", ".sh", ".app" ],
root_exclude_files = set(root_ignored_files),
root=False):
"""
Returns a list of source-filename, destination-filename pairs.
"""
if dest[0] != "/":
raise Exception("Destination must begin with /: %r" % dest)
src = src.rstrip('/')
dest = dest.rstrip('/')
def include(fn, is_root):
"""
Returns True if the file should be included in the list of
files we are copying.
"""
for i in exclude_suffix:
if fn.endswith(i):
return False
for i in exclude_prefix:
if fn.startswith(i):
return False
if fn in exclude_files:
return False
if not root or not is_root:
return True
for i in root_exclude_suffix:
if fn.endswith(i):
return False
for i in root_exclude_prefix:
if fn.startswith(i):
return False
if fn in root_exclude_files:
return False
return True
rv = [ ]
# Walk the tree, including what is necessary.
for srcdir, dirs, files in os.walk(src):
is_root = (srcdir == src)
srcdir += "/"
destdir = dest + srcdir[len(src):]
destdir.replace("\\", "/")
rv.append((srcdir, destdir))
for fn in files:
if not include(fn, is_root):
continue
sfn = srcdir + fn
dfn = destdir + fn
rv.append((sfn, dfn))
dirs[:] = [ i for i in dirs if include(i, is_root) ]
rv = [ (a.replace("\\", "/"), b.replace("\\", "/")) for a, b in rv ]
return rv
def make_zip(t, filename, files, file_data):
"""
This creates `filename`.zip, containing `files`, placed in the
`filename` directory. `file_data` is a map from source file to
replacement data.
"""
files.sort(key=lambda a : a[1])
progress_len = len(files)
fn = os.path.join(os.path.dirname(project.path), filename)
zf = MyZipFile(fn + ".zip", "w", zipfile.ZIP_DEFLATED)
for i, (fn, an) in enumerate(files):
progress(t, progress_len, i)
if os.path.isdir(fn):
continue
zi = zipfile.ZipInfo(filename + an)
s = os.stat(fn)
zi.date_time = time.gmtime(s.st_mtime)[:6]
zi.compress_type = zipfile.ZIP_DEFLATED
zi.create_system = 3
for i in executable_extensions:
if os.path.dirname(fn).endswith(i) or fn.endswith(i):
zi.external_attr = long(0100777) << 16
break
else:
zi.external_attr = long(0100666) << 16
if fn in file_data:
data = file_data[fn]
zf.writestr(zi, data)
else:
zf.write_file_with_zipinfo(fn, zi)
zf.close()
def make_tar(t, filename, files):
"""
Makes a tarfile, as above.
"""
files.sort(key=lambda a : a[1])
progress_len = len(files)
fn = os.path.join(os.path.dirname(project.path), filename)
tf = tarfile.open(fn + ".tar.bz2", "w:bz2")
tf.dereference = True
for j, (fn, an) in enumerate(files):
progress(t, progress_len, j)
info = tf.gettarinfo(fn, filename + an)
perms = 0666
if info.isdir():
perms = 0777
for i in executable_extensions:
if fn.endswith(i):
perms = 0777
info.mode = perms
info.uid = 1000
info.gid = 1000
info.uname = "renpy"
info.gname = "renpy"
if info.isreg():
tf.addfile(info, file(fn, "rb"))
else:
tf.addfile(info)
tf.close()
def dist_exists(fn):
"""
Returns true if the given file exists in the renpy directory.
"""
return os.path.exists(os.path.join(config.renpy_base, fn))
label distribute:
call lint
@@ -370,173 +155,18 @@ label distribute:
project.save()
base_name = base_name.encode("utf-8")
executable_name = executable_name.encode("utf-8")
ignore_extensions = ignore_extensions.encode("utf-8")
documentation_extensions = documentation_extensions.encode("utf-8")
# Convert some of these to more useful formats.
ignore_extensions = [ i.strip() for i in ignore_extensions.split() ]
documentation_extensions = [ i.strip() for i in documentation_extensions.split() ]
# Scan for the files we want to include in the various distributions.
info(_(u"Scanning..."), "")
# Files included in the various distributions.
multi_files = [ ]
win_files = [ ]
linux_files = [ ]
mac_files = [ ]
# A map from source file name to replacement data to be placed in
# that file.
file_data = { }
######################################################################
# Multi files.
rb = config.renpy_base.replace("\\", "/") + "/"
# Project files.
multi_files.extend(tree(project.path, "/", root=True, exclude_suffix=ignore_extensions))
multi_files.append((rb + "renpy.py", "/" + executable_name + ".py"))
# Renpy files.
multi_files.extend(tree(rb + "common", "/common"))
multi_files.extend(tree(rb + "renpy", "/renpy"))
multi_files.append((rb + "LICENSE.txt", "/renpy/LICENSE.txt"))
def add_script_version(fn, ignore_extensions=ignore_extensions, multi_files=multi_files, rb=rb):
"""
Add a script_version file if it does not already exist, and if the
extension is allowed by the game.
"""
for a, b in multi_files:
if b == "/game/" + fn:
return
for i in ignore_extensions:
if fn.endswith(i):
return
multi_files.append((rb + "launcher/" + fn, "/game/" + fn))
add_script_version("script_version.rpy")
add_script_version("script_version.rpyc")
######################################################################
# Windows files.
if build_windows or build_all:
win_files.append((rb + "renpy.exe", "/" + executable_name + ".exe"))
win_files.append((rb + "renpy.code", "/renpy.code"))
win_files.append((rb + "python25.dll", "/python25.dll"))
win_files.append((rb + "msvcr71.dll", "/msvcr71.dll"))
if os.path.exists(project.path + "/icon.ico"):
file_data[rb + "renpy.exe"] = pefile.change_icons(
rb + "renpy.exe",
project.path + "/icon.ico",
)
######################################################################
# Linux files.
if build_linux or build_all:
linux_files.append((rb + "renpy.sh", "/" + executable_name + ".sh"))
linux_files.append((rb + "lib", "/lib"))
linux_files.append((rb + "lib/python", "/lib/python"))
linux_files.extend(tree(rb + "lib/linux-x86", "/lib/linux-x86"))
# Warning: The tar.bz2 builder doesn't support file_data.
distribute.distribute(
project.path,
config.renpy_base,
base_name=base_name,
executable_name=executable_name,
ignore_extensions=ignore_extensions,
documentation_extensions=documentation_extensions,
build_windows=build_windows,
build_mac=build_mac,
build_linux=build_linux,
build_all=build_all)
######################################################################
# Mac (non-app) files.
if build_mac or build_all:
mac_files = tree(rb + "renpy.app",
"/" + executable_name + ".app")
# Rename executable.
mac_files = [ (fn, an.replace("Ren'Py Launcher", executable_name)) for (fn, an) in mac_files ]
# Plist file.
quoted_name = executable_name.replace("&", "&amp;").replace("<", "&lt;")
info_plist = file(rb + "renpy.app/Contents/Info.plist", "rb").read().replace("Ren'Py Launcher", quoted_name)
file_data[rb + "renpy.app/Contents/Info.plist"] = info_plist
# Launcher script.
quoted_name = executable_name.replace("\"", "\\\"")
launcher_py = file(rb + "renpy.app/Contents/Resources/launcher.py", "rb").read().replace("Ren'Py Launcher", quoted_name)
file_data[rb + "renpy.app/Contents/Resources/launcher.py"] = launcher_py
# Icon file.
if os.path.exists(project.path + "/icon.icns"):
icon_data = file(project.path + "/icon.icns", "rb").read()
file_data[rb + "renpy.app/Contents/Resources/launcher.icns"] = icon_data
######################################################################
# Now, build the various distributions.
if build_windows:
make_zip(
_(u"Building Windows..."),
base_name + "-win32",
multi_files + win_files,
file_data)
if build_linux:
make_tar(
_(u"Building Linux..."),
base_name + "-linux-x86",
multi_files + linux_files)
if build_mac:
# Reorganize the files so all the non application files live inside
# the application. If there's documentation involved, then it
# lives in both places.
macapp_files = [ ]
for fn, an in multi_files + mac_files:
if not an.startswith("/" + executable_name + ".app"):
new_an = "/" + executable_name + ".app/Contents/Resources/autorun" + an
macapp_files.append((fn, new_an))
if an.rindex('/') == 0:
for i in documentation_extensions:
if fn.endswith(i):
macapp_files.append((fn, an))
break
else:
macapp_files.append((fn, an))
make_zip(
_(u"Building Macintosh..."),
base_name + "-mac",
macapp_files,
file_data)
if build_all:
make_zip(
_(u"Building Combined..."),
base_name + "-all",
multi_files + win_files + linux_files + mac_files,
file_data)
# Report success to the user.
set_tooltip(_(u"Thank you for choosing Ren'Py."))
@@ -544,7 +174,7 @@ label distribute:
ui.vbox()
title(_(u"Success"))
text(_(u"The distributions have been built. Be sure to test them before release.\n\nNote that unpacking and repacking the Macintosh, Linux, or Combined distributions on Windows is not supported.\n\nPlease announce your release at the {a=http://lemmasoft.renai.us/forums/}Lemma Soft Forums{/a}, so we can add it to the Ren'Py web site."))
text(_(u"The distributions have been built. Be sure to test them before release.\n\nNote that unpacking and repacking the Macintosh, Linux, or Combined distributions on Windows is not supported.\n\nPlease announce your release at the {a=http://lemmasoft.renai.us/forums/}Lemma Soft Forums{/a}, and add it to {a=http://games.renpy.org}games.renpy.org{/a}."))
ui.null(height=20)
@@ -553,76 +183,3 @@ label distribute:
ui.close()
interact()
init python:
class MyZipFile(zipfile.ZipFile):
"""
Modified ZipFile class that can insert a file into the archive,
using a supplied ZipInfo object. Code comes from the writestr
and write methods of ZipFile.
"""
def write_file_with_zipinfo(self, filename, zinfo, compress_type=None):
"""Put the bytes from filename into the archive under the name
arcname."""
st = os.stat(filename)
if compress_type is None:
zinfo.compress_type = self.compression
else:
zinfo.compress_type = compress_type
zinfo.file_size = st.st_size
zinfo.flag_bits = 0x00
zinfo.header_offset = self.fp.tell() # Start of header bytes
self._writecheck(zinfo)
self._didModify = True
fp = open(filename, "rb")
# Must overwrite CRC and sizes with correct data later
zinfo.CRC = CRC = 0
zinfo.compress_size = compress_size = 0
zinfo.file_size = file_size = 0
self.fp.write(zinfo.FileHeader())
if zinfo.compress_type == zipfile.ZIP_DEFLATED:
cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
zlib.DEFLATED, -15)
else:
cmpr = None
while 1:
buf = fp.read(1024 * 64)
if not buf:
break
file_size = file_size + len(buf)
CRC = binascii.crc32(buf, CRC)
if cmpr:
buf = cmpr.compress(buf)
compress_size = compress_size + len(buf)
self.fp.write(buf)
fp.close()
if cmpr:
buf = cmpr.flush()
compress_size = compress_size + len(buf)
self.fp.write(buf)
zinfo.compress_size = compress_size
else:
zinfo.compress_size = file_size
zinfo.CRC = CRC
zinfo.file_size = file_size
# Seek backwards and write CRC and file sizes
position = self.fp.tell() # Preserve current position in file
self.fp.seek(zinfo.header_offset + 14, 0)
self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size,
zinfo.file_size))
self.fp.seek(position, 0)
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo
+21
View File
@@ -221,6 +221,27 @@ init 11 python:
interact()
def pauseinfo(t, message):
"""
Displays an error to the user, and lets him click to return to
`target`.
"""
set_tooltip("")
screen()
ui.vbox()
title(t)
text(message)
ui.null(height=20)
button(_(u"Ok"), ui.returns(True), None)
ui.close()
interact()
def info(t, message):
"""
Displays an informational message to the user, and immediately
+3
View File
@@ -100,6 +100,9 @@ init -1 python hide:
## Set this to False if the game does not have any sound effects.
config.sound = False
# Disable opengl.
config.gl_enable = False
python early:
config.save_directory = "launcher-2"
+3872 -302
View File
File diff suppressed because it is too large Load Diff
+6 -1
View File
@@ -4,6 +4,11 @@ init python:
import sys
import platform
import subprocess
# Set the projects directory to None if it no longer exists.
if persistent.projects_directory is not None:
if not os.path.isdir(persistent.projects_directory):
persistent.projects_directory = None
ZWSP = u"\u200B"
@@ -220,7 +225,7 @@ label launch:
set_tooltip(_(u"%s has been launched.") % project.name.capitalize())
store.game_proc = proc
jump top
+47
View File
@@ -0,0 +1,47 @@
def k(s):
s = s.replace(" ", "")
s = s.replace(":", "")
s = s.replace("\n", "")
return int(s, 16)
modulus = k("""
00:c2:e6:31:c6:7d:b3:cf:57:12:91:cf:b4:2c:9d:
25:17:cf:21:f8:ac:5b:1d:c1:95:56:9d:1c:1c:d5:
eb:67:ca:0a:a4:3f:e5:9c:6c:10:6e:4a:7a:2c:c2:
d6:e3:3f:84:6d:b1:6f:70:3d:05:4e:06:91:3c:51:
28:3f:b1:26:a5:be:6e:a6:14:a1:09:95:87:10:4d:
c3:4b:44:fd:e0:a6:9d:f8:1f:50:ca:8a:0d:fd:86:
7d:39:74:af:af:4e:05:8b:bd:93:b5:9b:6a:85:ca:
1e:47:25:ca:f1:31:47:10:3e:a2:26:79:d2:00:34:
f4:c5:a8:db:b6:36:2b:70:ef:14:8c:44:41:02:11:
64:31:d4:d8:cd:7b:a7:e1:af:25:2c:a4:31:fb:84:
c7:bc:6e:7c:fb:6a:46:5d:ee:bb:5f:74:96:a1:fe:
13:79:55:e8:c4:74:77:1c:ea:6a:8e:a8:cb:89:da:
20:db:88:18:e5:4a:f9:93:43:03:53:c3:d8:a3:2c:
73:ea:8c:64:55:da:cf:a5:c7:11:70:ce:d4:51:3c:
2c:19:06:3c:23:0c:d6:02:a5:95:28:b7:b0:34:1f:
5d:32:38:e0:01:f2:12:b5:b2:8f:6b:83:83:06:6c:
e0:ca:ec:e5:45:3e:75:79:f4:bf:47:e2:56:cd:8a:
7b:cc:c7:0d:14:af:00:f6:e0:64:e2:30:a3:6c:ed:
05:1e:33:9a:88:8b:0d:31:48:2b:02:65:61:4b:cd:
84:90:c5:83:ba:93:1f:b7:78:7f:ec:4e:e9:bc:02:
03:86:c2:a9:00:87:4c:e1:bb:d8:e7:b2:12:a6:9b:
ab:9f:24:6f:6d:fe:09:60:22:d9:45:c2:20:55:70:
27:9d:3a:84:fb:57:9a:d3:d0:d2:d3:18:25:8c:40:
f8:2c:15:98:de:2e:2d:be:b4:dd:6e:24:2b:07:0b:
21:08:a6:db:30:df:5c:7f:50:6f:be:b7:2e:40:28:
58:85:89:de:4e:c7:66:af:fc:05:1c:c7:4d:d1:d2:
fa:2c:00:1a:0e:47:5f:30:b6:e6:90:fe:99:96:42:
4d:17:d3:13:36:7b:76:1c:36:c6:31:f3:a8:b0:9c:
33:a1:b3:e9:40:51:b9:29:1d:b4:36:2a:20:0e:c0:
f7:fb:a9:db:18:e0:67:ca:5d:d7:46:03:17:32:04:
35:24:5a:fe:0a:1e:7b:96:8b:0a:fb:3c:f6:94:92:
ab:d8:7d:ed:e4:2b:64:d7:ab:8d:11:89:e3:80:9d:
28:59:da:de:6f:55:30:30:78:9a:06:30:5b:a4:ff:
7a:70:49:b6:8c:9a:66:c0:a8:77:74:ca:f5:02:05:
63:8c:83
""")
exponent = 0x10001
+7 -3
View File
@@ -83,7 +83,7 @@ label top:
_(u"Visit the Ren'Py games list, at http://games.renpy.org."))
button(_(u"Quit"),
renpy.quit,
ui.jumps("launcher_quit"),
_(u"Causes the launcher to exit."))
button(_(u"Options"),
@@ -105,11 +105,14 @@ label top:
ui.null()
ui.null()
ui.close()
ui.close()
if update_allowed:
ui.key("U", Jump("update"))
interact()
# ProcessBehavior can return True, which sends us here.
@@ -133,7 +136,8 @@ label renpy_games_list:
set_tooltip(_(u"Now showing the Ren'Py Games List in your web browser."))
jump top
label launcher_quit:
label confirm_quit:
$ renpy.quit()
+1 -1
View File
@@ -1,3 +1,3 @@
init -999:
$ config.script_version = (6, 10, 2)
$ config.script_version = (6, 11, 1)
+29 -21
View File
@@ -1,8 +1,13 @@
init python:
LAUNCHER_RPYS = set(['options.rpy', 'strings.rpy', 'transupdate.rpy', 'choose_theme.rpy', 'archiver.rpy', 'project.rpy', 'script_version.rpy', 'new.rpy', 'themes_data.rpy', 'opts.rpy', 'interface.rpy', 'projectsdir.rpy', 'distribute.rpy', 'script.rpy', 'editor.rpy'])
LAUNCHER_RPYS = set(['options.rpy', 'strings.rpy', 'transupdate.rpy', 'choose_theme.rpy', 'archiver.rpy', 'project.rpy', 'script_version.rpy', 'new.rpy', 'updater.rpy', 'themes_data.rpy', 'opts.rpy', 'interface.rpy', 'projectsdir.rpy', 'update_interface.rpy', 'distribute.rpy', 'script.rpy', 'editor.rpy'])
TRANSLATION_STRINGS = [
u"Graphics Acceleration",
u"Automatically Choose",
u"Prefer Software Renderer",
u"Prefer OpenGL Renderer",
u"Continue",
u"Are you sure?",
u"Are you sure you want to delete this save?",
u"Are you sure you want to overwrite your save?",
@@ -64,14 +69,13 @@ init python:
u"Joystick...",
u"Joystick Configuration",
u"Voice Volume",
u"Developer Menu",
u"Return to the developer menu",
u"Reload Game (Shift+R)",
u"Reload Game (Shift + R)",
u"Variable Viewer",
u"Return to the developer menu",
u"Theme Test",
u"Style Hierarchy",
u"FPS Meter",
u"Image Location Picker",
u"Filename List",
u"Done",
u"Auto",
u"Quick",
@@ -104,6 +108,16 @@ init python:
u"Choose Theme",
u"Please choose a color scheme for your project.",
u"Choose Color Scheme",
u"Base Name",
u"Please enter in the base name for your distribution. This name is used to generate the names of directories and archive files. Usually, this is the name of your game, plus a version number, like \"moonlight-1.0\".",
u"Executable Name",
u"Please enter a name for the executables in your distribution. This should not include an extension, as that will be added automatically.",
u"Ignore Extensions",
u"Please enter a space-separated list of file extensions. Files with these extensions will not be included in the built distributions.",
u"Documentation Extensions",
u"Please enter a space separated list of documentation extensions. Files in the base directory with these extensions will have a second copy stored outside of the Macintosh application.",
u"Thank you for choosing Ren'Py.",
u"The distributions have been built. Be sure to test them before release.\n\nNote that unpacking and repacking the Macintosh, Linux, or Combined distributions on Windows is not supported.\n\nPlease announce your release at the {a=http://lemmasoft.renai.us/forums/}Lemma Soft Forums{/a}, and add it to {a=http://games.renpy.org}games.renpy.org{/a}.",
u"Building Distributions",
u"I've just performed a lint on your project. If it contains errors, you should say no and fix them.\nPlease also check {a=http://www.renpy.org/wiki/renpy/Download_Ren'Py}www.renpy.org{/a} to see if updates or fixes are available.\n\nDo you want to continue?",
u"Base Name:",
@@ -125,21 +139,6 @@ init python:
u"Zip distribution for the Windows x86, Linux x86, Macintosh x86 and Macintosh ppc platforms.",
u"Build",
u"Start building the distributions.",
u"Base Name",
u"Please enter in the base name for your distribution. This name is used to generate the names of directories and archive files. Usually, this is the name of your game, plus a version number, like \"moonlight-1.0\".",
u"Executable Name",
u"Please enter a name for the executables in your distribution. This should not include an extension, as that will be added automatically.",
u"Ignore Extensions",
u"Please enter a space-separated list of file extensions. Files with these extensions will not be included in the built distributions.",
u"Documentation Extensions",
u"Please enter a space separated list of documentation extensions. Files in the base directory with these extensions will have a second copy stored outside of the Macintosh application.",
u"Scanning...",
u"Building Windows...",
u"Building Linux...",
u"Building Macintosh...",
u"Building Combined...",
u"Thank you for choosing Ren'Py.",
u"The distributions have been built. Be sure to test them before release.\n\nNote that unpacking and repacking the Macintosh, Linux, or Combined distributions on Windows is not supported.\n\nPlease announce your release at the {a=http://lemmasoft.renai.us/forums/}Lemma Soft Forums{/a}, so we can add it to the Ren'Py web site.",
u"The editor has been set from the RENPY_EDITOR environment variable, and cannot be changed.",
u"Choose Editor",
u"Please choose the editor that will be use to edit scripts and display errors. More editors can be downloaded from {a=http://www.renpy.org/wiki/renpy/Editors}the Ren'Py website{/a}.",
@@ -154,6 +153,7 @@ init python:
u"Something with that name already exists in the projects directory.",
u"Creating Project",
u"Please wait while we create the project.",
u"Could not create the project directory. The error was: %s",
u"%s Launcher",
u"Launcher Options",
u"Using RENPY_EDITOR",
@@ -177,7 +177,10 @@ init python:
u"Choose Projects Directory",
u"Please choose the directory containing your projects.",
u"Could not run zenity. The projects directory has been set to the directory immediately above the directory containing Ren'Py.",
u"Tutorial Game",
u"Launches the Ren'Py tutorial game.",
u"Update Ren'Py",
u"Updates Ren'Py to the latest version.",
u"Now showing the Ren'Py documentation in your web browser.",
u"Now showing the Ren'Py Games List in your web browser.",
u"Launch",
@@ -204,6 +207,11 @@ init python:
u"Change Ren'Py launcher options.",
u"Ren'Py Help",
u"Open the Ren'Py documentation in a web browser.",
u"Tutorial Game",
u"Retrieving catalog",
u"Checking files",
u"Making directories.",
u"Downloading updated files",
u"Renaming files",
u"Fixing permissions.",
]
+58
View File
@@ -0,0 +1,58 @@
# This is an early version of an interface for the updater. For now, we just
# assume that the user wants to update the prerelease channel, and the
# base tag.
init python:
import os
import time
version_fn = os.path.join(config.basedir, "lib", "update-version.txt")
update_allowed = os.path.exists(version_fn)
label update:
python hide:
try:
info("Checking for update...", "")
old_version = file(version_fn, "rb").read()
updater = Updater(config.basedir, 'http://update.renpy.org/renpy/updates/prerelease', [ 'base' ])
# Check the version.
version, verbose_version = updater.check_version(old_version)
if version is None:
pauseinfo("Up To Date", "Your version of Ren'Py is up to date.")
renpy.jump("top")
if not yesno("Update Available", "Would you like to update to %s?" % verbose_version):
renpy.jump("top")
# If we've made it this far, the user has decided that he wants
# to try an update.
for what, amount, limit in updater.step():
progress(what, limit, amount)
f = file(version_fn, "wb")
f.write(version)
f.close()
pauseinfo("Update complete.", "The update has finished. Ren'Py will now restart.")
if sys.platform == "win32" and sys.argv[0].lower().endswith(".exe"):
proc = subprocess.Popen([sys.argv[0], config.basedir])
else:
proc = subprocess.Popen([sys.executable, sys.argv[0], config.basedir])
renpy.quit()
except UpdateException, e:
error('The update has failed, with the error message: %s' % e.args[0])
+328
View File
@@ -0,0 +1,328 @@
init python:
import urllib2
import bz2
import os
import hashlib
import public
class UpdateException(Exception):
"""
The exception that we return if the update fails.
"""
pass
class Updater(object):
"""
A class that attempts to update a tree of files, with a reasonable
degree of safety, security, speed, and progress reporting.
"""
def __init__(self, local, remote, tags):
"""
Create a new updater.
`local`
The name of the local directory where the files are stored.
`remote`
The remote url base.
`tags`
A list of tags to update.
"""
self.local = local
self.remote = remote
# The remote version we're upgrading to.
self.version = None
# A list of directory names.
self.directories = [ ]
# A list of file, bz2-size, adler32 tuples.
self.files = [ ]
# Xbit files.
self.xbit = [ ]
# The tags we use.
self.tags = set(tags)
def snarf(self, url):
"""
Gets the url as a string.
"""
url = self.remote + "/" + url
try:
u = urllib2.urlopen(url, None, 5)
return u.read()
except Exception, e:
raise UpdateException("Could not download %r: %r" % (url, e))
def retrieve(self, relative):
"""
Downloads the bz2-compressed file, and then decompresses it into
relative.new.
"""
bz = os.path.join(self.local, relative + ".new.bz2")
new = os.path.join(self.local, relative + ".new")
url = self.remote + "/" + relative + ".bz2"
try:
u = urllib2.urlopen(url, None, 5)
f = file(bz, "wb")
f.write(u.read())
f.close()
u.close()
bzf = bz2.BZ2File(bz, "rb")
f = file(new, "wb")
while True:
buf = bzf.read(1024 * 1024)
if not buf:
break
f.write(buf)
f.close()
bzf.close()
os.unlink(bz)
except Exception, e:
raise UpdateException("Could not download %r: %r" % (url, e))
def check_version(self, version):
"""
Checks to see if version is still up to date. Returns a new-version,
verbose-version string. new-version is an internal representation
of the version being downloaded, while verbose-version is a
string that can be presented to the user.
The `version` argument should be given the new-version returned
from the last successful update. new-version is None if we are
up to date.
"""
remote_version = self.snarf("version")
self.version, verbose_version = remote_version.split("\n", 1)
self.version += " " + " ".join(sorted(self.tags))
if self.version.strip() == version.strip():
return None, verbose_version
else:
return self.version, verbose_version
def verify_hash(self, relative, digest):
"""
Verifies that the file `relative` has the hash value `digest`.
"""
fn = os.path.join(self.local, relative)
if not os.path.exists(fn):
return False
hash = hashlib.sha256()
try:
f = file(fn, "rb")
while True:
data = f.read(1024 * 1024)
if not data:
break
if not "renpy.app" in fn:
if fn.endswith(".rpy") or fn.endswith(".rpym") or fn.endswith(".py") or fn.endswith(".txt"):
data = data.replace("\n", "\r\n")
data = data.replace("\r\r\n", "\r\n")
hash.update(data)
f.close()
except:
return False
return hash.hexdigest() == digest
def get_catalog(self):
"""
Downloads the catalog file from the server, checking the signature
as necessary.
"""
self.retrieve("catalog1")
catalog_fn = os.path.join(self.local, "catalog1.new")
verified = False
try:
hash = hashlib.sha256()
f = file(catalog_fn, "rb")
# Read control information.
for l in f:
if l[0] == "-":
break
hash.update(l)
l = l[:-1]
a = l.split("\t")
if a[0] == "file":
cmd, digest, size, tag, name = a
if tag in self.tags:
self.files.append((name, digest, int(size)))
elif a[0] == "dir":
cmd, tag, name = a
if tag in self.tags:
self.directories.append(name)
elif a[0] == "xbit":
cmd, name = a
self.xbit.append(name)
else:
raise UpdateException("Unknown upgrade command: %r" % l)
# Compute the unsigned message.
unsigned = int("01" + hash.hexdigest(), 16)
for l in f:
a = l[:-1].split("\t")
if a[0] != "signature":
continue
signature = int(a[1], 16)
if pow(signature, public.exponent, public.modulus) == unsigned:
verified = True
f.close()
os.unlink(catalog_fn)
except UpdateException:
raise
except Exception, e:
raise UpdateException("Could not download catalog: %r" % (e,))
if not verified:
raise UpdateException("Could not verify catalog signature.")
def step(self):
"""
This is a generator that performs the steps in the update
process. It yields a (message, complete, total) tuple for
each step, and terminates upon success.
"""
yield (u"Retrieving catalog", 0, 1)
self.get_catalog()
updated_files = [ ]
download_size = 0
for i, (name, hash, size) in enumerate(self.files):
yield (u"Checking files", i, len(self.files))
if not self.verify_hash(name, hash):
updated_files.append((name, hash, size))
download_size += size
complete_size = 0
# Todo: Make directories.
for i, dir in enumerate(self.directories):
yield (u"Making directories", i, len(self.directories))
dir = os.path.join(self.local, dir)
if not os.path.exists(dir):
try:
os.mkdir(dir)
except:
raise UpdateException("Couldn't make directory %r." % dir)
complete = 0
for name, hash, size in updated_files:
yield (u"Downloading updated files", complete, len(updated_files))
if self.verify_hash(name + ".new", hash):
complete_size += size
continue
self.retrieve(name)
if not self.verify_hash(name + ".new", hash):
raise UpdateException("Could not verify download of %r." % name)
complete_size += size
complete += 1
umask = os.umask(0)
os.umask(umask)
for i, (name, hash, size) in enumerate(updated_files):
yield (u"Renaming files", i, len(updated_files))
fn = os.path.join(self.local, name)
if os.path.exists(fn + ".old"):
os.unlink(fn + ".old")
if os.path.exists(fn):
os.rename(fn, fn + ".old")
os.rename(fn + ".new", fn)
if fn.endswith(".py") and os.path.exists(fn + 'o'):
os.unlink(fn + 'o')
for i, name in enumerate(self.xbit):
yield (u"Fixing permissions", i, len(self.xbit))
fn = os.path.join(self.local, name)
if os.path.exists(fn):
os.chmod(fn, 0777 & (~umask))
# if __name__ == "__main__":
# up = Updater("/tmp/renpy-1", "file:///tmp/renpy-6.11.0", [ "base" ])
# version, verbose_version = up.check_version(1)
# for message, done, total in up.step():
# print message, "(%d/%d)" % (done, total)
# print version
# print verbose_version
-534
View File
@@ -1,534 +0,0 @@
# This file contains the code needed to build a Ren'Py distribution.
init python:
import zipfile
import tarfile
import os
import os.path
import time
import sys
import zlib
import pefile
# Returns true if a file or directory should not be included in
# the distribution
ignored_files = ("thumbs.db",
"launcherinfo.py",
"traceback.txt",
"errors.txt",
"icon.ico",
"icon.icns"
)
root_ignored_files = (
"common",
"renpy",
"renpy.code",
"python23.dll",
"python24.dll",
"python25.dll",
"msvcr71.dll",
"lib",
"iliad-icon.png",
"manifest.xml"
)
def ignored(fn, dir, dest, root):
if fn[0] == ".":
return True
for i in store.ignore_extensions:
if fn.endswith(i):
return True
if fn.lower() in ignored_files:
return True
if fn == "saves":
return True
if fn == "archived":
return True
if root and dir == dest:
if fn.endswith(".py") or fn.endswith(".sh") or fn.endswith(".app"):
return True
if fn in root_ignored_files:
return True
return False
def tree(src, dest,
exclude_suffix=[ ".pyc", "~", ".bak" ],
exclude_prefix=[ ".", '#' ],
exclude=ignored_files,
exclude_func=ignored,
root=False,
):
# Get rid of trailing slashes.
if src[-1] == "/":
src = src[:-1]
if dest and dest[-1] == "/":
dest = dest[:-1]
# What should we include?
def include(fn, destdir, dest):
for i in exclude_suffix:
if fn.endswith(i):
return False
for i in exclude_prefix:
if fn.startswith(i):
return False
for i in exclude:
if i == fn.lower():
return False
if exclude_func and exclude_func(fn, destdir, dest, root):
return False
return True
rv = [ ]
# Walk the tree, including what is necessary.
for srcdir, dirs, files in os.walk(src):
if dest:
destdir = dest + srcdir[len(src):]
else:
destdir = srcdir[len(src) + 1:]
if destdir:
rv.append((srcdir, destdir))
for fn in files:
if not include(fn, destdir, dest):
continue
sfn = srcdir + "/" + fn
if destdir:
dfn = destdir + "/" + fn
else:
dfn = fn
dfn = dfn.replace("\\", "/")
rv.append((sfn, dfn))
dirs[:] = [ i for i in dirs if include(i, destdir, dest) ]
return rv
label distribute:
python hide:
zlib.Z_DEFAULT_COMPRESSION = 9
store.progress_time = 0
def progress(tit, n, m, time=time):
if time.time() < store.progress_time + .1:
return
title(tit)
mid(message)
ui.bar(m, n, xmaximum=200, xalign=0.5)
ui.close()
ui.pausebehavior(0)
interact()
# Check to see which platforms we can build on.
if os.path.exists(config.renpy_base + "/renpy.exe"):
windows = True
else:
windows = False
if os.path.exists(config.renpy_base + "/lib/linux-x86"):
linux = True
else:
linux = False
if os.path.exists(config.renpy_base + "/lib/linux-iliad"):
iliad = True
else:
iliad = False
if os.path.exists(config.renpy_base + "/renpy.app"):
mac = True
else:
mac = False
if not (windows or mac or linux or iliad):
store.error(u"Can't Distribute", u"Ren'Py is missing files required for distribution. Please download the full package from {a=http://www.renpy.org/}www.renpy.org{/a}.", "tools_menu")
lint()
store.message = ""
title(_(u"Building Distributions"))
mid()
text(u"I've just performed a lint on your project. If it contains errors, you should say no and fix them.\nCheck {a=http://www.renpy.org/wiki/renpy/Download_Ren'Py}www.renpy.org{/a} to see if updates or fixes are available.\n\nDo you want to continue?")
ui.close()
bottom()
button(u"Yes", clicked=ui.returns(True))
button(u"No", clicked=ui.returns(False))
ui.close()
if not interact():
renpy.jump("tools")
# if not windows or not mac or not linux:
# store.message = "The full version of Ren'Py can build for Windows, Mac, and Linux. Download it from www.renpy.org."
title(u"Building Distributions")
mid()
text(u"Distributions will be built for the following platforms:")
spacer()
if windows:
text(u"Windows 2000+", style='launcher_input')
if linux:
text(u"Linux x86", style='launcher_input')
if iliad:
text(u"iLiad", style='launcher_input')
if mac:
text(u"Mac OS X 10.4+", style='launcher_input')
spacer()
# TODO: If missing platforms, prompt for a DL.
text(u"Is this okay?")
ui.close()
bottom()
button(u"Yes", clicked=ui.returns(True))
button(u"No", clicked=ui.returns(False))
ui.close()
if not interact():
renpy.jump("tools")
default_name = project.info.get('distribution_base', project.name)
name = prompt(u"Building Distributions",
u"Please enter a base name for the directories making up this distribution.",
"tools",
default_name,
u"This usually should include a name and version number, like 'moonlight_walks-1.0'.")
name = name.strip()
if not name:
store.error(u"Error", u"The distribution name should not be empty.", "tools_menu")
try:
name = name.encode("ascii")
except:
store.error(u"Error", u"Distribution names must be ASCII. This is because archive file formats do not support non-ASCII characters in a uniform way.", "tools_menu")
project.info['distribution_base'] = name
ignore_extensions = project.info.get('ignore_extensions', "~ .bak")
ignore_extensions = prompt(u"Building Distributions", u"Please enter a space separated list of the file extensions you do not want included in the distribution.", "tools", ignore_extensions)
store.ignore_extensions = [ i.strip() for i in ignore_extensions.strip().split() ]
project.info['ignore_extensions'] = ignore_extensions
project.save()
# Figure out the files that will make up the distribution.
multi = [ ]
# This finds the files and directories in the tree, and includes
# them in the result.
# renpy and common directories.
multi.extend(tree(config.renpy_base + "/renpy", "renpy"))
multi.append((config.renpy_base + "/LICENSE.txt", "renpy/LICENSE.txt"))
multi.extend(tree(config.commondir, "common"))
# Include the project.
multi.extend(tree(project.path, '',
exclude_suffix = [ ],
exclude_prefix = [ ],
exclude=[ ],
root=True))
shortgamedir = project.gamedir[len(project.path)+1:]
def add_script_version(fn, multi=multi, shortgamedir=shortgamedir):
for a, b in multi:
if b == shortgamedir + "/" + fn:
return
for i in store.ignore_extensions:
if fn.endswith(i):
return
multi.append((config.gamedir + "/" + fn, shortgamedir + "/" + fn))
add_script_version("script_version.rpy")
add_script_version("script_version.rpyc")
# renpy.py
multi.append((config.renpy_base + "/renpy.py",
project.name + ".py"))
# Windows Zip
if windows:
win_files = [
( config.renpy_base + "/renpy.exe", project.name + ".exe"),
( config.renpy_base + "/renpy.code", "renpy.code" ),
( config.renpy_base + "/python25.dll", "python25.dll" ),
( config.renpy_base + "/msvcr71.dll", "msvcr71.dll" ),
]
win_data = { }
if os.path.exists(project.path + "/icon.ico"):
win_data[project.name + ".exe"] = pefile.change_icons(
config.renpy_base + "/renpy.exe",
project.path + "/icon.ico",
)
zf = zipfile.ZipFile(name + ".zip", "w", zipfile.ZIP_DEFLATED)
progress_len = len(multi) + len(win_files)
store.message = u"Be sure to announce your project at the Lemma Soft Forums."
for i, (fn, an) in enumerate(multi + win_files):
progress(u"Building Windows", i, progress_len)
if os.path.isdir(fn):
continue
zi = zipfile.ZipInfo(name + "/" + an)
s = os.stat(fn)
zi.date_time = time.gmtime(s.st_mtime)[:6]
zi.compress_type = zipfile.ZIP_DEFLATED
zi.create_system = 3
zi.external_attr = long(0100666) << 16
data = file(fn, "rb").read()
data = win_data.get(an, data)
zf.writestr(zi, data)
zf.close()
# Linux Tar Bz2
if linux:
linux_files = [
(config.renpy_base + "/lib/linux-x86", "lib/linux-x86"),
(config.renpy_base + "/renpy.sh", project.name + ".sh"),
(config.renpy_base + "/lib/python", "lib/python"),
]
linux_files.extend(tree(config.renpy_base + "/lib/linux-x86", "lib/linux-x86"))
tf = tarfile.open(name + "-linux-x86.tar.bz2", "w:bz2")
tf.dereference = True
progress_len = len(multi) + len(linux_files)
store.message = u"If appropriate, please submit your game to www.renai.us."
for j, i in enumerate(multi + linux_files):
progress(u"Building Linux", j, progress_len)
fn, an = i
info = tf.gettarinfo(fn, name + "-linux-x86/" + an)
if info.isdir():
perms = 0777
elif info.name.endswith(".sh"):
perms = 0777
elif info.name.endswith(".so"):
perms = 0777
elif info.name.endswith("python"):
perms = 0777
elif info.name.endswith("python.real"):
perms = 0777
else:
perms = 0666
info.mode = perms
info.uid = 1000
info.gid = 1000
info.uname = "renpy"
info.gname = "renpy"
if info.isreg():
tf.addfile(info, file(fn, "rb"))
else:
tf.addfile(info)
tf.close()
# iLiad Tar Bz2
if iliad:
iliad_files = [
(config.renpy_base + "/lib", "lib"),
(config.renpy_base + "/renpy-iliad.sh", project.name + ".sh"),
(config.renpy_base + "/lib/python", "lib/python"),
(config.renpy_base + "/manifest.xml", "manifest.xml"),
(config.renpy_base + "/iliad-icon.png", "iliad-icon.png"),
]
iliad_files.extend(tree(config.renpy_base + "/lib/linux-iliad", "lib/linux-iliad"))
iliad_data = { }
manifest = file(config.renpy_base + "/manifest.xml", "r").read()
manifest = manifest.replace("GAMENAME", project.name)
iliad_data["manifest.xml"] = manifest
zf = zipfile.ZipFile(name + "-iLiad.zip", "w", zipfile.ZIP_DEFLATED)
progress_len = len(multi) + len(iliad_files)
store.message = u"We thank Hixbooks for sponsoring iLiad support."
for i, (fn, an) in enumerate(multi + iliad_files):
progress(u"Building iLiad", i, progress_len)
if os.path.isdir(fn):
continue
zi = zipfile.ZipInfo(project.name + "/" + an)
s = os.stat(fn)
zi.date_time = time.gmtime(s.st_mtime)[:6]
zi.compress_type = zipfile.ZIP_DEFLATED
zi.create_system = 3
for ext in [ ".sh", ".so", "python", "python.real" ]:
if fn.endswith(ext):
zi.external_attr = long(0100777) << 16
data = file(fn, "rb").read()
break
else:
zi.external_attr = long(0100666) << 16
data = file(fn, "rb").read()
data = iliad_data.get(an, data)
zf.writestr(zi, data)
zf.close()
if mac:
mac_files = tree(config.renpy_base + "/renpy.app",
project.name + ".app")
mac_files = [ (fn, an.replace("Ren'Py Launcher", project.name)) for (fn, an) in mac_files ]
# Data replacement for macintosh.
mac_data = { }
quoted_name = project.name.replace("&", "&amp;").replace("<", "&lt;")
info_plist = file(config.renpy_base + "/renpy.app/Contents/Info.plist", "rb").read().replace("Ren'Py Launcher", quoted_name)
mac_data[project.name + ".app/Contents/Info.plist"] = info_plist
quoted_name = project.name.replace("\"", "\\\"")
launcher_py = file(config.renpy_base + "/renpy.app/Contents/Resources/launcher.py", "rb").read().replace("Ren'Py Launcher", quoted_name)
mac_data[project.name + ".app/Contents/Resources/launcher.py"] = launcher_py
if os.path.exists(project.path + "/icon.icns"):
icon_data = file(project.path + "/icon.icns", "rb").read()
mac_data[project.name + ".app/Contents/Resources/launcher.icns"] = icon_data
zf = zipfile.ZipFile(name + "-mac.zip", "w", zipfile.ZIP_DEFLATED)
progress_len = len(multi) + len(mac_files)
store.message = u"Thank you for choosing Ren'Py."
for i, (fn, an) in enumerate(multi + mac_files):
progress(u"Building Mac OS X", i, progress_len)
if os.path.isdir(fn):
continue
zi = zipfile.ZipInfo(name + "-mac/" + an)
s = os.stat(fn)
zi.date_time = time.gmtime(s.st_mtime)[:6]
zi.compress_type = zipfile.ZIP_DEFLATED
zi.create_system = 3
if os.path.dirname(fn).endswith("MacOS") or fn.endswith(".so") or fn.endswith(".dylib"):
zi.external_attr = long(0100777) << 16
data = file(fn, "rb").read()
else:
zi.external_attr = long(0100666) << 16
data = file(fn, "rb").read()
data = mac_data.get(an, data)
zf.writestr(zi, data)
zf.close()
# Announce Success
store.message = ""
title(u"Success")
mid()
text(u"The distribution(s) have been built. Be sure to test them before release.")
spacer()
if mac:
text(u"Note that unpacking and repacking Mac zips and Linux tarballs on Windows isn't supported.")
ui.close()
bottom()
button(u"Return", clicked=ui.returns(True))
ui.close()
interact()
jump tools
-29
View File
@@ -1,29 +0,0 @@
# This file contains logic for detecting an editor, and for selecting
# the default editor.
init:
python hide:
import os
import os.path
import sys
if not config.editor:
editor = os.path.normpath(config.renpy_base + "/jedit/jedit.jar")
if os.path.exists(editor):
editor = renpy.shell_escape(editor)
if sys.platform == 'win32':
config.editor = 'javaw.exe -jar "' + editor + '" -reuseview "%(filename)s" +line:%(line)d "%(otherfiles)s"'
config.editor_transient = 'javaw.exe -jar "' + editor + '" -newplainview "%(filename)s" +line:%(line)d "%(otherfiles)s"'
else:
config.editor = 'java -jar "' + editor + '" -reuseview "%(filename)s" +line:%(line)d "%(otherfiles)s"'
config.editor_transient = 'java -jar "' + editor + '" -newplainview "%(filename)s" +line:%(line)d "%(otherfiles)s"'
if config.editor:
os.environ['RENPY_EDITOR'] = config.editor
if config.editor_transient:
os.environ['RENPY_EDITOR_TRANSIENT'] = config.editor_transient
Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

-792
View File
@@ -1,792 +0,0 @@
python early:
config.save_directory = "launcher-1"
init:
python:
# Set up the window.
config.screen_width = 350
config.screen_height = 450
config.window_title = "Ren'Py Launcher"
# Disable sound and joystick.
config.sound = False
config.joystick = False
# Disables autosave (we can't save/load)
config.has_autosave = False
# Create some launcher styles.
style.create('launcher_button', 'button')
style.create('launcher_button_text', 'button_text')
style.create('launcher_title_label', 'default')
style.create('launcher_label', 'default')
style.create('launcher_input', 'default')
style.create('launcher_text', 'default')
style.create('launcher_bottom_vbox', 'vbox')
style.create('launcher_mid_vbox', 'vbox')
style_backup = renpy.style.backup()
_launcher_per_page = 8
# Choose the roundrect theme for the buttons.
layout.compat()
theme.roundrect(launcher=True)
style.hyperlink_text.color = "#0ff"
config.underlay = [
renpy.Keymap(
quit = renpy.quit_event,
iconify = renpy.iconify,
)
]
def quote(c):
n = ord(c)
if 0x20 <= n <= 0x7f:
return c
else:
return "\\x%02x" % n
def ifrw(label):
if project.info.get("ro", False):
return None
else:
return ui.jumps(label)
# We don't want the user going into the game menu.
def interact():
ui.window(background=Solid("#0008"), ypos=1.0, yminimum=80, xmargin=0, ymargin=0)
ui.null()
ui.image("eileen_small.png", xalign=0.0, yalign=1.0)
ui.add(DynamicDisplayable("Text(_(store.message), size=14, color='#fff', xpos=100, ypos=375, xmaximum=240)"))
ui.text(renpy.version(), xalign=0, yalign=1.0, size=12, color='#000')
return ui.interact()
def title(name):
ui.window(style='mm_root')
ui.null()
ui.frame(xminimum=350, yminimum=370)
ui.viewport(child_size=(2000, None), draggable=True, ymaximum=34)
_label_factory(name, "launcher_title", size=28)
# ui.text(name, xpos=4, ypos=4, size=30, color="#559")
def text(name, style="launcher_text"):
ui.text(_(name), style=style)
def label(name):
_label_factory(name, "launcher")
def spacer():
ui.add(Null(1, 6))
def mid(focus="mid"):
ui.vbox(style='launcher_mid_vbox', focus=focus)
def bottom(focus="bottom"):
ui.vbox(style='launcher_bottom_vbox', focus=focus)
def button(text, hover_text=None, clicked=None, hovered=None, selected=False):
if hover_text:
def hovered(hover_text=_(hover_text)):
if store.message != hover_text:
store.message = hover_text
renpy.restart_interaction()
# ui.button(clicked=clicked, hovered=hovered)
# ui.text(text, style="button_text")
_button_factory(text, 'launcher', clicked=clicked, hovered=hovered, selected=selected, xmaximum=200)
def prompt(name, message, cancel, default='', hint=''):
store.message = _(hint)
# Creating the project.
title(name)
mid()
text(message)
ui.input(default, exclude='{}/\\', style='launcher_input')
ui.close()
bottom()
button("Cancel", clicked=ui.jumps("main"))
ui.close()
return interact()
def error(name, message, target):
store.message = ''
# Creating the project.
title(name)
mid()
text(message)
ui.close()
bottom()
button("Cancel", clicked=ui.jumps(target))
ui.close()
return interact()
def paged_menu(tit, choices, message, per_page=None, cancel='main'):
if per_page is None:
per_page = _launcher_per_page
page = 0
pages = (len(choices) - 1) / per_page
while True:
store.message = message
title(tit)
mid(focus="paged_menu")
for name, desc, ret, hovered, selected in choices[page * per_page:(page + 1) * per_page]:
if len(name) > 19:
name = name[:18] + u"\u2026"
button(name, desc, clicked=ui.returns(("return", ret)), hovered=hovered, selected=selected)
ui.close()
bottom()
if pages >= 1:
if page < pages:
button(u"Next Page", u"Go to the next page of projects.", clicked=ui.returns(("page", page + 1)))
else:
button(u"Next Page")
if page > 0:
button(u"Previous Page", u"Go to the previous page of projects.", clicked=ui.returns(("page", page - 1)))
else:
button(u"Previous Page")
button(u"Cancel", u"Return to the top menu.", ui.jumps(cancel))
ui.close()
cmd, arg = interact()
if cmd == "repeat":
continue
if cmd == "page":
page = arg
continue
if cmd == "return":
return arg
class ProcessBehavior(renpy.display.layout.Null):
def __init__(self, proc):
super(ProcessBehavior, self).__init__()
self.proc = proc
def event(self, ev, x, y, st):
if self.proc.poll() is not None:
return True
renpy.game.interface.timeout(.25)
class Project(object):
def __init__(self, name, path, gamedir, info):
# name
self.name = name
# path to project
self.path = path
# gamedir
self.gamedir = gamedir
self.info = info
import re
def upper(m):
return m.group(0).upper()
title = re.sub(r'^.', upper, name)
title = re.sub(r'\s+\S', upper, title)
self.title = title
def save(self):
import os
f = file(self.path + "/" + "launcherinfo.py.new", "w")
for k, v in self.info.iteritems():
f.write("%s = %r\n" % (k, v))
f.close()
try:
os.rename(self.path + "/launcherinfo.py.new", self.path + "/launcherinfo.py")
except:
os.unlink(self.path + "/launcherinfo.py")
os.rename(self.path + "/launcherinfo.py.new", self.path + "/launcherinfo.py")
def load_project(dir, name):
import os.path
# Ignore unicode files.
for i in name:
if ord(i) >= 127:
return
if os.path.isdir(dir + "/game"):
gamedir = dir + "/game"
elif os.path.isdir(dir + "/data"):
gamedir = dir + "/data"
else:
return
desc = u""
info = dict()
info["description"] = desc
if os.path.exists(dir + "/launcherinfo.py"):
source = file(dir + "/launcherinfo.py", "rU").read().decode("utf8")
if source[0] == u'\ufeff':
source = source[1:]
source = source.encode("raw_unicode_escape")
exec source in info
del info["__builtins__"]
store.projects.append(Project(name, dir, gamedir, info))
def load_projects():
import os
import os.path
store.projects = [ ]
cwd = os.getcwd()
if cwd == config.renpy_base:
dirs = [ cwd ]
else:
dirs = [ config.renpy_base, cwd ]
for d in dirs:
contents = os.listdir(d)
contents.sort()
for dd in contents:
dir = d + "/" + dd
if os.path.isdir(dir):
load_project(dir, dd)
if not store.projects:
raise Exception("The launcher will not function without any projects.")
def lint():
import renpy.subprocess as subprocess
import sys
import os.path
store.message = u"Lint in progress."
title(u"Lint")
ui.pausebehavior(0)
interact()
lf = file("lint.txt", "w+")
if hasattr(sys, "winver") and sys.argv[0].lower().endswith(".exe"):
proc = subprocess.Popen([config.renpy_base + "/console.exe", "--lint", project.path], stdin=lf, stdout=lf, stderr=lf)
else:
proc = subprocess.Popen([sys.executable, sys.argv[0], "--lint", project.path], stdout=lf)
proc.wait()
lf.close()
renpy.launch_editor([ "lint.txt" ],transient=1)
def rmpersistent():
import renpy.subprocess as subprocess
import sys
import os.path
store.message = u"Deleting persistent data."
title(u"Delete Persistent")
ui.pausebehavior(0)
interact()
if hasattr(sys, "winver") and sys.argv[0].lower().endswith(".exe"):
proc = subprocess.Popen([config.renpy_base + "/console.exe", "--rmpersistent", project.path])
else:
proc = subprocess.Popen([sys.executable, sys.argv[0], "--rmpersistent", project.path])
proc.wait()
label main_menu:
return
label find_project:
python hide:
load_projects()
wanted = persistent.project or "demo"
for p in projects:
if p.name == wanted:
store.project = p
break
else:
store.project = projects[0]
store.game_proc = None
return
label start:
call find_project from _call_find_project_1
label main:
python:
store.message = u"What do you want to do?"
label top_menu:
python hide:
while True:
title(project.title)
mid()
label(u"This Project")
if not game_proc or game_proc.poll() is not None:
clicked = ui.jumps("launch")
else:
clicked = None
button(u"Launch",
u"Starts the project running.",
clicked=clicked)
if config.editor:
button(u"Edit Script",
u"Edits the script files.",
clicked=ui.jumps("edit"))
button(u"Change Theme",
u"Changes the color theme of the project.",
ifrw("choose_theme"))
button(u"Game Directory",
u"Opens the game directory.",
clicked=ui.jumps("game_directory"))
button(u"Tools",
u"Shows the tools menu.",
clicked=ui.jumps("tools"))
spacer()
label(u"Change Project")
button(u"Select Project",
u"Select a project to work with.",
clicked=ui.jumps("select_project"))
button(u"New Project",
u"Create a new project from a template.",
clicked=ui.jumps("new"))
ui.close()
bottom()
button(u"Documentation", u"Read Ren'Py tutorials and manuals.", clicked=ui.jumps("documentation"))
button(u"Quit", u"Quit the Ren'Py Launcher.", clicked=ui.jumps("confirm_quit"))
ui.close()
if game_proc and game_proc.poll() is None:
ui.add(ProcessBehavior(game_proc))
interact()
jump top_menu
label select_project:
python hide:
choices = [ (p.name, p.info["description"], p, None, False) for p in projects if not p.info.get("template") ]
store.project = paged_menu(u"Select a Project", choices, u"Please select a project.")
persistent.project = store.project.name
store.game_proc = None
jump main
label launch:
python hide:
import renpy.subprocess
import sys
import os.path
import os
if hasattr(sys, "winver") and sys.argv[0].lower().endswith(".exe"):
proc = renpy.subprocess.Popen([sys.argv[0], project.path])
else:
proc = renpy.subprocess.Popen([sys.executable, sys.argv[0], project.path])
store.message = _(u"%s has been launched.") % project.title
store.game_proc = proc
jump top_menu
label edit:
python hide:
import os
files = [ project.gamedir + "/" + i for i in os.listdir(project.gamedir) if i.endswith(".rpy") if not i[0] == "."]
files.sort()
for i in files[:]:
if i.endswith("options.rpy"):
files.remove(i)
files.insert(0, i)
for i in files[:]:
if i.endswith("script.rpy"):
files.remove(i)
files.insert(0, i)
if not renpy.launch_editor(files):
error(u"Error", u"Launching the editor failed. You may need Java, which can be downloaded for free from {a=http://www.java.com}java.com{/a}.", "start")
store.message = _(u"Launched editor with %d script files.") % len(files)
jump top_menu
label game_directory:
python hide:
import os
import os.path
import platform
import sys
gamedir = os.path.normpath(project.gamedir)
if sys.platform == "win32":
os.startfile(gamedir)
elif platform.mac_ver()[0]:
import renpy.subprocess as subprocess
subprocess.Popen([ "open", gamedir ])
else:
import renpy.subprocess as subprocess
subprocess.Popen([ "xdg-open", gamedir ])
gamedir = "".join(quote(i) for i in gamedir)
store.message = _(u"Opening game directory:\n%s") % gamedir
jump top_menu
label tools:
$ store.message = u"Please choose a tool you want to use with this project."
label tools_menu:
python hide:
title(_("Tools: %s") % project.title)
mid()
label(u"Anytime")
button(u"Check Script (Lint)",
u"Checks the game's script for likely errors. This should be run before releasing.",
clicked=ui.jumps("lint"))
button(u"Delete Persistent",
u"Deletes the game's persistent data.",
clicked=ui.jumps("rmpersistent"))
# button("Quick Backup",
# "Makes a backup copy of the project. You also need to make backups somewhere other then this computer.",
# clicked=ui.jumps("backup"))
spacer()
label(u"Release Day")
button(u"Add From to Calls",
u"Adds a from clause to each of the call statements in your script.",
clicked=ifrw("add_from_to_calls"))
button(u"Archive Files",
u"Archive files found under the game and archived directories.",
clicked=ifrw("archive_files"))
button(u"Build Distributions",
u"Build distributions for the platforms supported by Ren'Py.",
clicked=ui.jumps("distribute"))
ui.close()
bottom()
button(u"Back",
u"Goes back to the top menu.",
clicked=ui.jumps("main"))
ui.close()
interact()
label lint:
python hide:
lint()
store.message = u"A lint report should appear shortly."
jump tools_menu
label archive_files:
python hide:
import os
import os.path
import renpy.tools.archiver as archiver
extensions = project.info.get('archive_extensions', "*.png *.gif *.jpg")
extensions = prompt(u"Archiving Files", u"Please enter a space separated list of the file patterns you want archived.", "tools", extensions)
if not extensions.strip():
renpy.jumps("tools_menu")
project.info['archive_extensions'] = extensions
extensions = [ i.strip() for i in extensions.strip().split() ]
base = project.info.get('archive_base', "data")
base = prompt(u"Archiving Files", u"Please enter the name of the archive file, without the .rpa extension.", "tools", base)
base = base.strip()
if not base:
renpy.jumps("tools_menu")
project.info['archive_base'] = base
project.save()
# Tell the user we're archiving images.
title(u"Archiving Files")
store.message = u"Please wait while we archive files."
ui.pausebehavior(0)
interact()
gamedir = project.gamedir
archived = project.path + "/archived"
files = [ ]
prefix = gamedir + "/" + base
def should_archive(fn, extensions=extensions):
import fnmatch
fn = fn.lower()
if fn[0] == ".":
return False
if fn == "presplash.png":
return False
if fn == "presplash.jpg":
return False
for e in extensions:
if fnmatch.fnmatch(fn, e):
return True
return False
archived_files = set()
for bdir in (gamedir, archived):
for dirname, dirs, filenames in os.walk(bdir):
# Ignore svn.
dirs[:] = [ i for i in dirs if not i[0] == '.' ]
for fn in filenames:
fullfn = dirname + "/" + fn
shortfn = fullfn[len(bdir)+1:]
if shortfn in archived_files:
continue
if not should_archive(shortfn):
continue
files.append((fullfn, shortfn))
archived_files.add(shortfn)
archiver.archive(prefix, files)
# f = file(gamedir + "/images.rpy", "w")
# print >>f, "init:"
# print >>f, " $ config.archives.append('images')"
# f.close()
for fullfn, shortfn in files:
afn = archived + "/" + shortfn
if fullfn == afn:
continue
try:
os.makedirs(os.path.dirname(afn))
except:
pass
try:
os.rename(fullfn, afn)
except:
os.rename(afn, afn + ".old")
os.rename(fullfn, afn)
os.unlink(afn + ".old")
store.message = u"The files have been added to the archive, and moved into the archived directory."
jump tools_menu
label backup:
python hide:
import os
import time
import shutil
# Tell the user we're archiving images.
title(u"Making Backup")
store.message = u"Please wait while we make a backup."
ui.pausebehavior(0)
interact()
try:
os.mkdir('backups')
except:
pass
while True:
btime = str(int(time.time()))
bdir = "backups/%s.%s" % (project.name, btime)
if not os.path.exists(bdir):
break
time.sleep(1)
shutil.copytree(project.path, bdir)
store.message = _(u"The backup was placed into %s.") % bdir
jump tools_menu
label add_from_to_calls:
python hide:
import os
import time
import shutil
title(u"Add From to Calls")
store.message = u"Please wait while we add from clauses to call statements."
ui.pausebehavior(0)
interact()
import renpy.tools.add_from as add_from
add_from.add_from(project.gamedir, config.commondir)
store.message = _(u"Done adding from clauses to call statements. You may want to remove the .bak files created.")
jump tools_menu
label rmpersistent:
python hide:
rmpersistent()
store.message = _(u"Done deleting persistent data.")
jump tools_menu
label confirm_quit:
$ renpy.quit()
label documentation:
python hide:
import webbrowser
webbrowser.open_new("file:///" + config.renpy_base + "/doc/index.html")
store.message = _(u"Now showing the Ren'Py documentation in your web browser.")
jump top_menu
-167
View File
@@ -1,167 +0,0 @@
label new:
python hide:
import os
import os.path
import time
# Select a template.
choices = [ (p.name, p.info["description"], p, None, False) for p in projects if p.info.get("template", None)]
template = paged_menu(u"Select a Template", choices, u"Please select a project to use as a template for your project.")
# Choose project name.
name = prompt(u"Project Name", u"Type the name of your new project, and press enter.\n", "main")
name = name.strip()
error = None
if not name:
error = u"Please enter a non-empty project name."
elif os.path.exists(name):
error = u"A file or directory named '%s' already exists." % name
else:
try:
name = name.encode("ascii")
except:
error = u"Project names must be ASCII. This is because the ZIP file format does not support non-ASCII characters in a uniform way."
if error:
store.error(u"Error", error, "main")
# Tell the user we're creating the project.
title(u"Creating Project")
store.message = u"Please wait while we create the project."
ui.pausebehavior(0)
interact()
# Here is where we actually create the project.
import shutil
shutil.copytree(template.path, name)
unlink = template.info.get("unlink", [ ])
unlink += [ 'launcherinfo.py' ]
for i in unlink:
if os.path.exists(name + "/" + i):
os.unlink(name + "/" + i)
for dir, dirs, files in os.walk(name):
for d in list(dirs):
if d.startswith("."):
dirs.remove(d)
dn = dir + "/" + d
shutil.rmtree(dn, True)
# Change the save directory.
options = file(name + "/game/options.rpy").read()
save_dir = "%s-%d" % (name, time.time())
options = options.replace("template-1220804310", save_dir)
file(name + "/game/options.rpy", "w").write(options)
persistent.project = name
call find_project from _call_find_project_2
label choose_theme:
python hide:
# Select a color scheme.
themes = theme_data.keys()
themes.sort()
choices = [ ]
for i in themes:
def hovered(i=i):
td = theme_data[i].copy()
engine = td["theme"]
del td["theme"]
if engine == "roundrect":
renpy.style.restore(style_backup)
theme.roundrect(launcher=True, **td)
renpy.style.rebuild()
return ("repeat", 0)
choices.append((i, None, i, hovered, False))
color_theme = paged_menu(u"Select a Theme", choices, u"Please select a color theme for your project. You can always change the colors later.", cancel='color_theme_cancel')
# Restore default theme.
renpy.style.restore(style_backup)
theme.roundrect(launcher=True)
renpy.style.rebuild()
ofn = project.path + "/game/options.rpy"
import os
import re
if not os.path.exists(ofn):
error(u"Changing Theme", u"The options file does not seem to exist.", "main")
inf = file(ofn, "rU")
outf = file(ofn + ".new", "w")
td = theme_data[color_theme]
# TODO: Make this less specific to roundrect. Need to figure out
# how to switch themes, rather than just recolor them.
changing = False
changed = False
for l in inf:
if re.match(r'\s*theme.roundrect\(', l):
changing = True
changed = True
elif re.match(r'\s*\)', l):
changing = False
elif changing:
def repl(m, td=td):
return m.group(1) + m.group(2) + " = \"" + td.get(m.group(2), m.group(3)) + "\","
l = re.sub(r'^(\s*)(\w+) = "([\da-fA-F#]+)",', repl, l)
outf.write(l)
outf.close()
inf.close()
try:
os.rename(ofn + ".new", ofn)
except:
# I hate windows.
os.rename(ofn, ofn + ".old")
os.rename(ofn + ".new", ofn)
os.unlink(ofn + ".old")
if not changed:
error(u"Changing Theme", u"Could not modify options.rpy, perhaps it was edited too much.", "main")
jump main
label color_theme_cancel:
python hide:
# Restore default theme.
renpy.style.restore(style_backup)
theme.roundrect(launcher=True)
renpy.style.rebuild()
jump main
-244
View File
@@ -1,244 +0,0 @@
init 1 python:
theme_data = {'Basic Blue': {'disabled': '#404040',
'disabled_text': '#c8c8c8',
'frame': '#6496c8',
'gm_root': '#dcebff',
'label': '#ffffff',
'mm_root': '#dcebff',
'theme': 'roundrect',
'widget': '#003c78',
'widget_hover': '#0050a0',
'widget_selected': '#ffffc8',
'widget_text': '#c8ffff'},
'Bloody Mary': {'disabled': '#400000',
'disabled_text': '#260000',
'frame': '#400808',
'gm_root': '#000000',
'label': '#ffffff',
'mm_root': '#000000',
'theme': 'roundrect',
'widget': '#000000',
'widget_hover': '#830000',
'widget_selected': '#ffffff',
'widget_text': '#C2C2C2'},
'Colorblind': {'disabled': '#898989',
'disabled_text': '#666666',
'frame': '#252525',
'gm_root': '#393939',
'label': '#c2c2c2',
'mm_root': '#393939',
'theme': 'roundrect',
'widget': '#898989',
'widget_hover': '#464646',
'widget_selected': '#F2F2F2',
'widget_text': '#CCCCCC'},
'Cotton Candy': {'disabled': '#C8AFA1',
'disabled_text': '#E1D4C9',
'frame': '#FCF5F2',
'gm_root': '#D0B4BA',
'label': '#805C40',
'mm_root': '#D0B4BA',
'theme': 'roundrect',
'widget': '#ECC7D0',
'widget_hover': '#E1D4C9',
'widget_selected': '#805C40',
'widget_text': '#805C40'},
'Creamsicle': {'disabled': '#FFECBF',
'disabled_text': '#ffffff',
'frame': '#FFECBF',
'gm_root': '#FDF5E3',
'label': '#502F13',
'mm_root': '#FDF5E3',
'theme': 'roundrect',
'widget': '#D96B00',
'widget_hover': '#FD9B1C',
'widget_selected': '#ffffff',
'widget_text': '#FCE6B1'},
'Dramatic Flesh': {'disabled': '#ab6038',
'disabled_text': '#BF7C51',
'frame': '#49271b',
'gm_root': '#2a201f',
'label': '#ffffff',
'mm_root': '#2a201f',
'theme': 'roundrect',
'widget': '#BF7C51',
'widget_hover': '#dda570',
'widget_selected': '#ffffff',
'widget_text': '#E5DFDF'},
'Easter Baby': {'disabled': '#DDE9FF',
'disabled_text': '#A6AFBF',
'frame': '#CCF8DC',
'gm_root': '#FBF9DF',
'label': '#698071',
'mm_root': '#FBF9DF',
'theme': 'roundrect',
'widget': '#F5D4EE',
'widget_hover': '#F0DDFF',
'widget_selected': '#000000',
'widget_text': '#698071'},
'Favorite Jeans': {'disabled': '#919994',
'disabled_text': '#B6BFB9',
'frame': '#6f7571',
'gm_root': '#b0b8ba',
'label': '#ffffff',
'mm_root': '#b0b8ba',
'theme': 'roundrect',
'widget': '#8699a7',
'widget_hover': '#9eb1ad',
'widget_selected': '#ffffff',
'widget_text': '#dcdfd6'},
'Fine China': {'disabled': '#ADB9CC',
'disabled_text': '#DFBA14',
'frame': '#ADB9CC',
'gm_root': '#F7F7FA',
'label': '#39435E',
'mm_root': '#F7F7FA',
'theme': 'roundrect',
'widget': '#6A7183',
'widget_hover': '#1A2B47',
'widget_selected': '#E3E3E4',
'widget_text': '#C9C9CB'},
'First Valentines': {'disabled': '#F8F2D0',
'disabled_text': '#BFA1A1',
'frame': '#F8F2D0',
'gm_root': '#D98989',
'label': '#5D1010',
'mm_root': '#D98989',
'theme': 'roundrect',
'widget': '#F09898',
'widget_hover': '#D6C5BB',
'widget_selected': '#B31E1E',
'widget_text': '#593131'},
'Ice Queen': {'disabled': '#F0F2F2',
'disabled_text': '#FBFBFB',
'frame': '#ffffff',
'gm_root': '#E6E6E6',
'label': '#D9D9D9',
'mm_root': '#E6E6E6',
'theme': 'roundrect',
'widget': '#D9D9D9',
'widget_hover': '#F0F2F2',
'widget_selected': '#737373',
'widget_text': '#ffffff'},
'Mocha Latte': {'disabled': '#614D3A',
'disabled_text': '#80654D',
'frame': '#926841',
'gm_root': '#1A140E',
'label': '#F1EBE5',
'mm_root': '#1A140E',
'theme': 'roundrect',
'widget': '#4D3B29',
'widget_hover': '#996E45',
'widget_selected': '#ffffff',
'widget_text': '#B99D83'},
'Muted Horror': {'disabled': '#73735C',
'disabled_text': '#8C8C70',
'frame': '#555544',
'gm_root': '#1A0001',
'label': '#1A0001',
'mm_root': '#1A0001',
'theme': 'roundrect',
'widget': '#777777',
'widget_hover': '#73735C',
'widget_selected': '#000000',
'widget_text': '#404033'},
'Old Polaroid': {'disabled': '#A89E7D',
'disabled_text': '#CCC097',
'frame': '#49403E',
'gm_root': '#A84A3E',
'label': '#ffffff',
'mm_root': '#A84A3E',
'theme': 'roundrect',
'widget': '#A89E7D',
'widget_hover': '#8DB6B9',
'widget_selected': '#ffffff',
'widget_text': '#49403E'},
'Really Red': {'disabled': '#404040',
'disabled_text': '#c8c8c8',
'frame': '#e17373',
'gm_root': '#ffd0d0',
'label': '#ffffff',
'mm_root': '#ffd0d0',
'theme': 'roundrect',
'widget': '#963232',
'widget_hover': '#c83232',
'widget_selected': '#ffffc8',
'widget_text': '#ffffff'},
'Summer Sky': {'disabled': '#6074BF',
'disabled_text': '#7383BF',
'frame': '#6074BF',
'gm_root': '#B4CDD4',
'label': '#94C7D4',
'mm_root': '#B4CDD4',
'theme': 'roundrect',
'widget': '#F2E6AA',
'widget_hover': '#FCFCA4',
'widget_selected': '#1A5766',
'widget_text': '#7DA8B3'},
'Swamp Critter': {'disabled': '#A2521D',
'disabled_text': '#753D00',
'frame': '#797C1C',
'gm_root': '#B09D5A',
'label': '#ffffff',
'mm_root': '#B09B4F',
'theme': 'roundrect',
'widget': '#753D00',
'widget_hover': '#B19A48',
'widget_selected': '#ffffff',
'widget_text': '#CCCAC2'},
'Urban Sprawl': {'disabled': '#8F0000',
'disabled_text': '#333333',
'frame': '#8F0000',
'gm_root': '#000000',
'label': '#ffffff',
'mm_root': '#000000',
'theme': 'roundrect',
'widget': '#333333',
'widget_hover': '#000000',
'widget_selected': '#ffffff',
'widget_text': '#6C8A2F'},
'Victorian Gingerbread': {'disabled': '#7A674F',
'disabled_text': '#664F33',
'frame': '#BF8A73',
'gm_root': '#695640',
'label': '#F2EDC4',
'mm_root': '#695640',
'theme': 'roundrect',
'widget': '#7A674F',
'widget_hover': '#BDA77D',
'widget_selected': '#FDFBEE',
'widget_text': '#F2EDC4'},
'Watermelon Pie': {'disabled': '#FABF46',
'disabled_text': '#FFE06D',
'frame': '#C3CD91',
'gm_root': '#F7F7C5',
'label': '#FCFCD7',
'mm_root': '#F7F7C5',
'theme': 'roundrect',
'widget': '#FFE06D',
'widget_hover': '#E38A4F',
'widget_selected': '#996600',
'widget_text': '#FAA700'},
'White Chocolate': {'disabled': '#614D3A',
'disabled_text': '#80654D',
'frame': '#926841',
'gm_root': '#FBF9EA',
'label': '#F1EBE5',
'mm_root': '#FBF9EA',
'theme': 'roundrect',
'widget': '#33271C',
'widget_hover': '#ECE7C4',
'widget_selected': '#ffffff',
'widget_text': '#B99D83'},
'Winter Mint': {'disabled': '#426143',
'disabled_text': '#819981',
'frame': '#245536',
'gm_root': '#e5f1e5',
'label': '#ffffff',
'mm_root': '#e5f1e5',
'theme': 'roundrect',
'widget': '#7AA27B',
'widget_hover': '#A3C7A3',
'widget_selected': '#ffffff',
'widget_text': '#CDE0CE'}}
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env python
import sys
sys.path.append('/home/tom/ab/keys/')
import os
import bz2
import hashlib
import public
import private
import shutil
def sha(s):
"""
Hashes s into a string.
"""
hash = hashlib.sha256()
hash.update(s)
return hash.hexdigest()
def make_update(root, version):
# A list of command strings.
commands = [ ]
for dir, dirs, files in os.walk(root):
for fn in files:
fn = os.path.join(dir, fn)
oldf = file(fn, "rb")
bzf = bz2.BZ2File(fn + ".bz2", "wb")
bzf.write(oldf.read())
bzf.close()
oldf.close()
shutil.copymode(fn, fn + ".bz2")
os.unlink(fn)
for dir, dirs, files in os.walk(root):
for fn in dirs + files:
path = os.path.join(dir, fn)
relpath = os.path.relpath(path, root)
if relpath in [ "version", "catalog1.bz2" ]:
continue
if os.path.isdir(path):
commands.append(('dir', "base", relpath))
elif relpath.endswith(".rpyc.bz2"):
continue
elif relpath.endswith(".rpymc.bz2"):
continue
elif relpath.endswith(".rpyb.bz2"):
continue
elif relpath.endswith(".pyo.bz2"):
continue
elif relpath.endswith(".bz2"):
hash = sha(bz2.BZ2File(path, "r").read())
size = "%d" % (os.path.getsize(path))
commands.append(('file', hash, size, "base", relpath[:-4]))
if os.access(path, os.X_OK):
commands.append(('xbit', relpath[:-4]))
out = bz2.BZ2File(os.path.join(root, "catalog1.bz2"), "w")
hash = hashlib.sha256()
for i in commands:
line = "\t".join(i) + "\n"
hash.update(line)
out.write(line)
unsigned = int("01" + hash.hexdigest(), 16)
signed = pow(unsigned, private.exponent, public.modulus)
out.write("-\n")
out.write("signature\t%x\n" % signed)
out.close()
f = file(os.path.join(root, "version"), "w")
f.write(version)
f.write("\n")
f.write("the latest Ren'Py pre-release")
f.close()
File diff suppressed because it is too large Load Diff
+425
View File
@@ -0,0 +1,425 @@
# This file contains bindings to integrate pygame (SDL) and OpenGL.
cdef extern from "pygame/pygame.h":
struct SDL_Surface:
int w
int h
int pitch
void *pixels
SDL_Surface *PySurface_AsSurface(object)
cdef extern from "GL/glew.h":
ctypedef unsigned int GLenum
ctypedef unsigned char GLboolean
ctypedef unsigned int GLbitfield
ctypedef void GLvoid
ctypedef signed char GLbyte
ctypedef short GLshort
ctypedef int GLint
ctypedef unsigned char GLubyte
ctypedef unsigned short GLushort
ctypedef unsigned int GLuint
ctypedef int GLsizei
ctypedef float GLfloat
ctypedef float GLclampf
ctypedef double GLdouble
ctypedef double GLclampd
GLenum GLEW_OK
GLenum glewInit()
GLubyte *glewGetErrorString(GLenum)
int GL_UNPACK_ROW_LENGTH
int GL_PACK_ROW_LENGTH
void glPixelStorei(
GLint pname,
GLint param)
int GL_TEXTURE_2D
int GL_RGBA8
int GL_RGBA
int GL_BGRA
int GL_ALPHA
int GL_UNSIGNED_BYTE
void glTexImage2D(
GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLint border,
GLenum format,
GLenum type,
void *pixels)
void glTexSubImage2D(
int target,
int level,
int xoffset,
int yoffset,
int width,
int height,
int format,
int type,
void *pixels)
GLenum GL_TEXTURE0_ARB
GLenum GL_TEXTURE1_ARB
GLenum GL_TEXTURE2_ARB
GLenum GL_TRIANGLE_STRIP
void glMultiTexCoord2fARB(GLenum, GLfloat, GLfloat)
void glVertex2f(GLfloat, GLfloat)
void glBegin(GLenum)
void glEnd()
void glActiveTextureARB(GLenum)
void glBindTexture(GLenum, GLuint texture)
GLubyte *glGetString(GLenum)
void glReadPixels(
GLint,
GLint,
GLsizei,
GLsizei,
GLenum,
GLenum,
void *)
def init_glew():
err = glewInit()
if err != GLEW_OK:
raise Exception("Glew init failed: %s" % <char *> glewGetErrorString(err))
def premultiply(
object pysurf,
int x,
int y,
int w,
int h,
border_left, border_top, border_right, border_bottom):
"""
Creates a string containing the premultiplied image data for
for the (x, y, w, h) box inside pysurf. The various border_
parameters control the addition of a border on the sides.
"""
# Adjust the alpha if we have an alpha-free image.
cdef unsigned char alpha_and
cdef unsigned char alpha_or
if pysurf.get_masks()[3]:
alpha_and = 255
alpha_or = 0
else:
alpha_and = 0
alpha_or = 255
# Allocate an uninitialized string.
cdef unsigned char *null = NULL
rv = null[:w*h*4]
# Out is where we put the output.
cdef unsigned char *out = rv
# The pixels in the source image.
cdef unsigned char *pixels = NULL
cdef SDL_Surface *surf
# Pointer to the current pixel.
cdef unsigned char *p
# Pointer to the current output pixel.
cdef unsigned char *op
# Pointer to the row end.
cdef unsigned char *pend
# alpha value.
cdef unsigned int a
# pixel pointer.
cdef unsigned int *pp
surf = PySurface_AsSurface(pysurf)
pixels = <unsigned char *> surf.pixels
pixels += y * surf.pitch
pixels += x * 4
op = out
for y from 0 <= y < h:
p = pixels + y * surf.pitch
pend = p + w * 4
while p < pend:
a = (p[3] & alpha_and) | alpha_or
op[0] = p[0] * a / 255
op[1] = p[1] * a / 255
op[2] = p[2] * a / 255
op[3] = a
p += 4
op += 4
if border_left:
pp = <unsigned int *> (out)
for y from 0 <= y < h:
pp[0] = pp[1]
pp += w
if border_right:
pp = <unsigned int *> (out)
pp += w - 2
for y from 0 <= y < h:
pp[1] = pp[0]
pp += w
if border_top:
pp = <unsigned int *> (out)
for x from 0 <= x < w:
pp[0] = pp[w]
pp += 1
if border_top:
pp = <unsigned int *> (out)
pp += (y - 2) * w
for x from 0 <= x < w:
pp[w] = pp[0]
pp += 1
return rv
def load_premultiplied(
data, width, height, update, format,
):
cdef char *pixels
if data:
pixels = data
else:
pixels = NULL
if update:
glTexSubImage2D(
GL_TEXTURE_2D,
0,
0,
0,
width,
height,
format,
GL_UNSIGNED_BYTE,
pixels)
else:
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA,
width,
height,
0,
format,
GL_UNSIGNED_BYTE,
pixels)
def store_framebuffer(
object pysurf,
int format,
):
"""
This loads the supplied pygame surface into the numbered
texture. The created texture will be of size (width, height),
and at position (xoffset, yoffset) relative to the containing
image.
"""
cdef unsigned char *pixels = NULL
cdef SDL_Surface *surf
surf = PySurface_AsSurface(pysurf)
pixels = <unsigned char *> surf.pixels
glPixelStorei(GL_PACK_ROW_LENGTH, surf.pitch / 4)
glReadPixels(
0,
0,
surf.w,
surf.h,
format,
GL_UNSIGNED_BYTE,
pixels)
def draw_rectangle(
float sx,
float sy,
float x,
float y,
float w,
float h,
transform,
tex0, int tex0x, int tex0y,
tex1, int tex1x, int tex1y,
tex2, int tex2x, int tex2y,
):
"""
This draws a rectangle (textured with up to four textures) to the
screen.
"""
# Do we have the given texture?
cdef int has_tex0, has_tex1, has_tex2
# Texture coordinates.
cdef float t0u0, t0v0, t0u1, t0v1
cdef float t1u0, t1v0, t1u1, t1v1
cdef float t2u0, t2v0, t2u1, t2v1
# Pull apart the transform.
cdef float xdx = transform.xdx
cdef float xdy = transform.xdy
cdef float ydx = transform.ydx
cdef float ydy = transform.ydy
# Transform the vertex coordinates to screen-space.
cdef float x0 = (x + 0) * xdx + (y + 0) * xdy + sx
cdef float y0 = (x + 0) * ydx + (y + 0) * ydy + sy
cdef float x1 = (x + w) * xdx + (y + 0) * xdy + sx
cdef float y1 = (x + w) * ydx + (y + 0) * ydy + sy
cdef float x2 = (x + 0) * xdx + (y + h) * xdy + sx
cdef float y2 = (x + 0) * ydx + (y + h) * ydy + sy
cdef float x3 = (x + w) * xdx + (y + h) * xdy + sx
cdef float y3 = (x + w) * ydx + (y + h) * ydy + sy
# Compute the texture coordinates, and set up the textures.
cdef float xadd, yadd, xmul, ymul
if tex0 is not None:
has_tex0 = 1
glActiveTextureARB(GL_TEXTURE0_ARB)
glBindTexture(GL_TEXTURE_2D, tex0.number)
xadd = tex0.xadd
yadd = tex0.yadd
xmul = tex0.xmul
ymul = tex0.ymul
t0u0 = xadd + xmul * (tex0x + 0)
t0u1 = xadd + xmul * (tex0x + w)
t0v0 = yadd + ymul * (tex0y + 0)
t0v1 = yadd + ymul * (tex0y + h)
else:
has_tex0 = 0
if tex1 is not None:
has_tex1 = 1
glActiveTextureARB(GL_TEXTURE1_ARB)
glBindTexture(GL_TEXTURE_2D, tex1.number)
xadd = tex1.xadd
yadd = tex1.yadd
xmul = tex1.xmul
ymul = tex1.ymul
t1u0 = xadd + xmul * (tex1x + 0)
t1u1 = xadd + xmul * (tex1x + w)
t1v0 = yadd + ymul * (tex1y + 0)
t1v1 = yadd + ymul * (tex1y + h)
else:
has_tex1 = 0
if tex2 is not None:
has_tex2 = 1
glActiveTextureARB(GL_TEXTURE2_ARB)
glBindTexture(GL_TEXTURE_2D, tex2.number)
xadd = tex2.xadd
yadd = tex2.yadd
xmul = tex2.xmul
ymul = tex2.ymul
t2u0 = xadd + xmul * (tex2x + 0)
t2u1 = xadd + xmul * (tex2x + w)
t2v0 = yadd + ymul * (tex2y + 0)
t2v1 = yadd + ymul * (tex2y + h)
else:
has_tex2 = 0
# Now, actually draw the textured rectangle.
glBegin(GL_TRIANGLE_STRIP)
if has_tex0:
glMultiTexCoord2fARB(GL_TEXTURE0_ARB, t0u0, t0v0)
if has_tex1:
glMultiTexCoord2fARB(GL_TEXTURE1_ARB, t1u0, t1v0)
if has_tex2:
glMultiTexCoord2fARB(GL_TEXTURE2_ARB, t2u0, t2v0)
glVertex2f(x0, y0)
if has_tex0:
glMultiTexCoord2fARB(GL_TEXTURE0_ARB, t0u1, t0v0)
if has_tex1:
glMultiTexCoord2fARB(GL_TEXTURE1_ARB, t1u1, t1v0)
if has_tex2:
glMultiTexCoord2fARB(GL_TEXTURE2_ARB, t2u1, t2v0)
glVertex2f(x1, y1)
if has_tex0:
glMultiTexCoord2fARB(GL_TEXTURE0_ARB, t0u0, t0v1)
if has_tex1:
glMultiTexCoord2fARB(GL_TEXTURE1_ARB, t1u0, t1v1)
if has_tex2:
glMultiTexCoord2fARB(GL_TEXTURE2_ARB, t2u0, t2v1)
glVertex2f(x2, y2)
if has_tex0:
glMultiTexCoord2fARB(GL_TEXTURE0_ARB, t0u1, t0v1)
if has_tex1:
glMultiTexCoord2fARB(GL_TEXTURE1_ARB, t1u1, t1v1)
if has_tex2:
glMultiTexCoord2fARB(GL_TEXTURE2_ARB, t2u1, t2v1)
glVertex2f(x3, y3)
glEnd()
def get_string(name):
return <char *> glGetString(name)
+10266
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -785,6 +785,7 @@ static void video_image_display(VideoState *is)
rect.y = is->ytop + y;
rect.w = width;
rect.h = height;
SDL_DisplayYUVOverlay(vp->bmp, &rect);
} else {
#if 0
@@ -1125,7 +1126,7 @@ static void alloc_picture(void *opaque, PyObject *pysurf)
is->video_st->codec->height,
SDL_YV12_OVERLAY,
surf);
vp->width = is->video_st->codec->width;
vp->height = is->video_st->codec->height;
+3515
View File
File diff suppressed because it is too large Load Diff
+275
View File
@@ -0,0 +1,275 @@
TEGL
----
Tegl is Python script for generating OpenGL extenstions. I wrote it
because I was disappointed with some other OpenGL solutions for
Python.
Tegl generates a C extension that can be compiled into module to make
OpenGL available to Python programs. (You're on your own compiling
it, though.)
Unlike PyOpenGL, the C extension is a thin wrapper around OpenGL. It
performs only minor argument checking. Nevertheless, it is mostly
compatible with PyOpenGL, and depending on how the module is
generated, it should only need minor changes to migrate from PyOpenGL.
(In fact, I was able to migrate a recent application simply by adding
a couple wrapper functions that mimicked PyOpenGL semantics.)
This is version 002.
USAGE
-----
To use, simply run maketegl.py. It will generate two files, tegl.c
and teglu.c in the current directory, which you can compile it to
create Python GL and GLU modules. The modules comprise (most of)
OpenGL 1.1.
For more control, open maketegl.py with a text editor. At the top are
some options for controlling the generated code. You can change the
names of the modules, and even combine them into one. You can control
whether the "gl" and "GL_" prefixes appear on the exported symbols.
You can choose to include or exclude various OpenGL extensions, or use
more recent versions of OpenGL. I recommend plain OpenGL 1.1 for
maximum portability, and selected ARB extensions if you need more.
There are some other switches I will cover below.
If you really want fine-tuned control, you can scroll past the options
and comment out any functions and constants you don't want. This may
be a good idea since currently Tegl modules are quite large when
compiled.
USING THE MODULE
----------------
Calling OpenGL functions is simple. Just import the module with "from
tegl import *" (or just "import tegl as gl" if you have built it
without prefixes, or whatever else suits you).
Most OpenGL functions can be called just as in C:
glBegin(GL_COMPILE) or gl.Begin(gl.COMPILE)
glVertex3d(1.0,2.0,3.0) or gl.Vertex3d(1.0,2.0,3.0)
glEnable(GL_CULL_FACE)
glRotated(1.0,90.0,0.0,0.0)
texon = glIsEnabled(GL_TEXTURE_2D)
It's usually pretty straightforward to use OpenGL functions that
accept data through a pointer: you just pass it a list (or tuple, or
numpy array, or any sequence).
glVertex3dv([1.0,2.0,3.0])
glMaterialfv(GL_FRONT,GL_AMBIENT,[0.2,0.2,0.2,1.0])
OpenGL functions that return data through a pointer are somewhat
trickier, you have to pass it an empty sequence that is large enough
to contain the data the function returns. The sequence type has to be
mutable, of course.
retval = [None]*4
glGetMaterialfv(GL_FRONT,GL_AMBIENT,retval)
(This is a departure from how PyOpenGL operates; it will simply create
an array and return it. But Tegl is intended to be a thin wrapper, so
it follows the C usage closely.)
In many cases, it's preferrable to use a buffer object instead of a
Python sequence to pass data to the function; for instance, texture
data. In these cases, you would pass in an object that supports
buffer protocol, such as a string, a numpy array, or an array from the
array module.
imagedata = Image.open(imgfile).tostring()
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,256,256,0,GL_RGBA,
GL_UNSIGNED_BYTE,imagedata)
To use an OpenGL function that returns image data, you need to pass in
a object that supports writable buffer protocol. The buffer must be
large enough to hold the output of the function, otherwise Bad Things
can happen. Strings are not mutable so you'll have to use some other
type. Arrays from the array module can be your friend here.
retval = array.array("B",[0])*640*480*4
glReadPixels(0,0,640,480,GL_RGBA,GL_UNSIGNED_BYTE,retval)
The question is, how do you know whether you should pass a buffer type
or a sequence type to OpenGL? (Currently, you can only pass one or
the other; this may change in a future version.) Here is the general
rule of thumb:
You need to use a buffer if:
* The type of the argument in C is GLvoid* (or just void*)
* OR the size of the data is theoretically unbounded.
You need to use a sequence if:
* The type if te argument is not GLvoid*
* AND the size of the data is fixed or bounded.
So glMaterialfv takes a sequence argument because it has a type
(GLfloat*) and has a size of 4 at most (it's bounded). On the other
hand, glTexImage2D uses a buffer argument because the type of the data
is GLvoid*, and the image can be arbitrarily large.
This rule of thumb does not always hold, however. I decided to go
against it where it seemed useful.
Several functions for modifying textures (glGenTextures,
glDeleteTextures, glPrioritizeTextures, and glAreTexturesResident)
accept arrays of unbounded size, but I felt that sequence types were
far more useful here, so I defined a constant (MAX_TEXTURE_ARRAY_SIZE)
that lets the user specify a bound on the size. (Otherwise I would
have had to muck around with malloc, and I did not want to do that.)
Functions for creating and destroying buffer object, occlusion
queries, and shader programs (ARB only) are treated likewise.
glCallList accepts buffer objects. Even though the size of the call
list is unbounded, it seemed as if a sequence would be more
appropriate. However, a common use case of glCallList (in conjunction
with glListBase) is to pass it a string, where each character is the
name of a display list that draws that character. Thus I left is as a
buffer.
If I chose wrongly for your application, I apologize. Numpy arrays
and arrays from the array module implement both the sequence and
buffer protocols; these may be of assistence to you. (Be careful
about numpy strides, though.)
If worse comes to worst, you can change the definition inside the
maketegl.py script to suit you.
ADVANCED: THE GIL
-----------------
It's possible that if you send a lot of data to the OpenGL pipeline
quickly enough, the OpenGL pipeline could fill up, an an OpenGL call
in progress would block until the pipeline clears up. This is
possible with functions like glCallList, which runs a display list
that could be enormous.
In threaded programs, the time spent waiting for an OpenGL block could
be used for other tasks. In Python, only a single thread can run
Python code at a given time (a thread has to have the GIL, global
interpreter lock, to run Python code). However, extensions may
release the GIL while not manipulating Python objects (which is the
case during an OpenGL call).
Therefore, there is an option in Tegl for releasing the GIL around
certain OpenGL calls, thus allowing other Python code to run if it
should happen to block. Simply add the name of the function (without
the "gl") to the set of functions to release the GIL for at the top of
maketegl.py.
UNSUPPORTED FUNCTIONS
---------------------
There are a few OpenGL functions that aren't supported by Tegl simply
because they have an unusual signature that the machinery doesn't
easily support. In this early release, I didn't bother. Here's the
list:
glGetString
glGetPointerv
glMultiDrawArrays(ARB)
glMultiDrawElements(ARB)
glGetBufferPointerv(ARB)
glGetVertexAttribPointerv(ARB)
glShaderSource(ARB)
All glu* functions that implement nurbs, tesselators, and quadrics.
Additionally, a couple functions are supported with limited
functionality:
glMapBuffer(ARB) returns a CObject. This is not too useful from
Python; however, you can get at it from a C extension. Also, ctypes
and numpy wizards should be able to map a numpy array to the pointer
location.
glShaderSource(ARB) is handcoded, and only supports passing it a
single string. (You must still pass a singleton sequence of strings;
this is to preserve upward compatibility.) For instance, you'd call
it like this:
glShaderSourceARB(shaderobj,1,[source],[len(source)])
IMPROVEMENTS
------------
The two main improvements I have in mind (aside from fixing up bugs
and adding stuff) are these:
* To take advantage of the parallelism of OpenGL to make the tegl
module a lot smaller. Many OpenGL function have the same signature
(same argument and return types) and I can save a lot of code by
generating one function with that signature, and calling it with a
function pointer (and maybe a size index or two).
* To support sequences and buffers for the same argument at the same
time. This isn't as straightforward as it looks, though, since for
objects that support both protocols, the results could be different
depending on whether it's treated as a buffer or a sequence. I have
to figure out what the most reasonable behavior is.
BUGS
----
Yes.
CHANGES FROM 001
----------------
Added #define GL_EXT_PROTOTYPES. Since Tegl depends on the C compiler
having prototypes available for typecasting arguments, this is pretty
important.
Added handcoded version of glShaderSource(ARB) that only accepts a
single string in the source.
Fixed specification of gluUnProject4.
LICENCE AND COPYRIGHT
---------------------
maketegl.py and maketegl.txt are copyrighted by Carl Banks.
These files, which comprise the tegl package, are released under a BSD
style license. See the file copying for details.
WHY NOT PYOPENGL
----------------
The standard OpenGL package in Python, PyOpenGL, has some limitations
(mostly speedwise) that made it undesirable for me.
Probably the biggest bottleneck is that PyOpenGL calls glGetError
after every call. I understand the rationale for this, but its cost
is too high for my needs. Another problem is, as far as I know, it
does not allow the user to release the GIL around some GL calls.
Thirdly, PyOpenGL 3 is based on ctypes. There's nothing wrong with
ctypes, but for a usage where speed really does matter, it's much too
slow. PyOpenGL 2 is a C extension, and is much faster than PyOpenGL
3, but doesn't support recent OpenGL extensions.
A minor thing I didn't like was that PyOpenGL didn't get rid of the gl
prefixes. I prefer namespaces, and would prefer to simply import a gl
module and call functions this way: "gl.End()". But PyOpenGL did not
support that; I had to write wrappers to pull the symbols apart.
But the most irritating thing about PyOpenGL is the setuptools entry
points, which mean that you cannot simply import the OpenGL modules;
you have to go through setuptools. This, among other things, makes
distributing programs using PyOpenGL (such as with py2exe) a pain.
+64 -22
View File
@@ -4,6 +4,7 @@ import os
import os.path
import platform
import sys
import subprocess
try:
import bdist_mpkg
@@ -105,7 +106,26 @@ def add_library(name, optional=False):
for i in checked:
print "-", i
sys.exit(-1)
def cython(fn):
"""
Use cython to generate `fn`.c from `fn`.pyx, if necessary.
"""
c = fn + ".c"
pyx = fn + ".pyx"
if not os.path.exists(pyx):
print pyx, "not in current directory, not running cython."
return
if os.path.exists(c) and os.path.getmtime(c) >= os.path.getmtime(pyx):
print pyx, "is not newer than", c
return
subprocess.call(["cython", pyx])
add_include("", "zlib.h")
add_include("", "png.h")
add_include("SDL", "SDL.h")
@@ -115,6 +135,7 @@ add_include("", "libavutil/avstring.h")
add_include("", "libavformat/avformat.h")
add_include("", "libavcodec/avcodec.h")
add_include("", "libswscale/swscale.h")
add_include("", "GL/glew.h")
add_library("libSDL")
add_library("libpng")
@@ -126,6 +147,16 @@ add_library("libfreetype")
add_library("libfribidi")
add_library("libz")
has_libglew = add_library("libGLEW", True)
has_libglew32 = add_library("libglew32", True)
cython("_renpy")
cython("_renpybidi")
cython("_renpy_pysdlgl")
cython("sound")
cython("winmixer")
extra_link_args = [ ]
sdl_libraries = [ 'SDL' ]
@@ -154,7 +185,7 @@ except:
extensions = [ ]
py_modules = [ 'pysdlsound.__init__' ]
rpe = distutils.core.Extension(
extensions.append(distutils.core.Extension(
"_renpy",
[ "IMG_savepng.c", "core.c", "rwobject.c", "_renpy.c", "subpixel.c" ],
include_dirs=include_dirs,
@@ -162,11 +193,9 @@ rpe = distutils.core.Extension(
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
libraries=sdl_libraries + png_libraries,
)
))
extensions.append(rpe)
renpy_font = distutils.core.Extension(
extensions.append(distutils.core.Extension(
"_renpy_font",
[ "renpy_ttf.c", "renpy_font.c"],
include_dirs=include_dirs,
@@ -174,11 +203,9 @@ renpy_font = distutils.core.Extension(
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
libraries=sdl_libraries + [ 'freetype', 'z' ],
)
))
extensions.append(renpy_font)
psse = distutils.core.Extension(
extensions.append(distutils.core.Extension(
"pysdlsound.sound",
[ "pss.c", "rwobject.c", "sound.c", "ffdecode.c" ],
include_dirs=include_dirs,
@@ -186,37 +213,52 @@ psse = distutils.core.Extension(
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
libraries=sound_libraries + sdl_libraries,
)
))
extensions.append(psse)
if winmixer:
wme = distutils.core.Extension(
extensions.append(distutils.core.Extension(
"pysdlsound.winmixer",
[ 'winmixer.c' ],
libraries=['winmm'],
)
extensions.append(wme)
))
if linmixer:
py_modules.append('pysdlsound.linmixer')
renpybidi = distutils.core.Extension(
extensions.append(distutils.core.Extension(
"_renpybidi",
["_renpybidi.c", "renpybidicore.c"],
include_dirs=include_dirs,
library_dirs=library_dirs,
libraries=['fribidi'],
)
))
extensions.append(renpybidi)
if has_libglew:
glew_libs = [ 'GLEW' ]
else:
glew_libs = [ 'glew32', "opengl32" ]
extensions.append(distutils.core.Extension(
"_renpy_tegl",
["_renpy_tegl.c"],
extra_compile_args=extra_compile_args,
include_dirs=include_dirs,
library_dirs=library_dirs,
libraries=glew_libs))
extensions.append(distutils.core.Extension(
"_renpy_pysdlgl",
["_renpy_pysdlgl.c"],
extra_compile_args=extra_compile_args,
include_dirs=include_dirs,
library_dirs=library_dirs,
libraries=glew_libs))
distutils.core.setup(
name = "renpy_module",
version = "6.10.1",
version = "6.11.0",
ext_modules = extensions,
py_modules = py_modules,
package_dir = { '' : 'lib' },
-1
View File
@@ -1 +0,0 @@
dist/msvcr71.dll
BIN
View File
Binary file not shown.
-13
View File
@@ -1,13 +0,0 @@
#!/bin/sh
rm -Rf spline_editor/*~
rm -Rf spline_editor/game/*~
rm -Rf spline_editor/game/*.rpyc
rm -Rf spline_editor/game/*.rpyb
rm -Rf spline_editor/game/saves
rm spline_editor.zip
zip -9r spline_editor.zip spline_editor -x \*.svn\*
-1
View File
@@ -1 +0,0 @@
dist/renpy.exe
-877
View File
@@ -1,877 +0,0 @@
# Ren'Py Visual Novel Engine
# Copyright (C) 2009 PyTom <pytom@bishoujo.us>
# This file is distributed under the same license as the Ren'Py package.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: mainline\n"
"Report-Msgid-Bugs-To: PyTom <pytom@bishoujo.us>\n"
"POT-Creation-Date: 2009-06-27 23:09-0400\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: common/00developer.rpy:18
#, python-format
msgid "Developer Menu"
msgstr ""
#: common/00developer.rpy:190 common/00developer.rpy:78
#, python-format
msgid "Return to the developer menu"
msgstr ""
#: common/00library.rpy:221
#, python-format
msgid "Skip Mode"
msgstr ""
#: common/00library.rpy:224
#, python-format
msgid "Fast Skip Mode"
msgstr ""
#: common/00library.rpy:307
#, python-format
msgid "While Ren'Py games may be playable without the renpy module, some features may be disabled. For more information, read the module/README.txt file or go to http://www.bishoujo.us/renpy/."
msgstr ""
#: common/00library.rpy:310
#, python-format
msgid "renpy module not found."
msgstr ""
#: common/00library.rpy:311
#, python-format
msgid "The renpy module could not be loaded on your system."
msgstr ""
#: common/00library.rpy:313
#, python-format
msgid "Old renpy module found."
msgstr ""
#: common/00library.rpy:314
#, python-format
msgid "An old version (%d) of the Ren'Py module was found on your system, while this game requires version %d."
msgstr ""
#: common/00library.rpy:498
#, python-format
msgid "Please click to continue."
msgstr ""
#: common/00menus.rpy:14 common/_compat/mainmenu.rpym:7
#, python-format
msgid "Start Game"
msgstr ""
#: common/00menus.rpy:15 common/00menus.rpy:25 common/_compat/gamemenu.rpym:13
#, python-format
msgid "Load Game"
msgstr ""
#: common/00menus.rpy:16 common/00menus.rpy:23 common/_compat/gamemenu.rpym:11 common/_compat/mainmenu.rpym:9
#, python-format
msgid "Preferences"
msgstr ""
#: common/00menus.rpy:17 common/00menus.rpy:27
#, python-format
msgid "Help"
msgstr ""
#: common/00menus.rpy:18 common/00menus.rpy:28 common/_compat/gamemenu.rpym:15 common/_compat/mainmenu.rpym:10
#, python-format
msgid "Quit"
msgstr ""
#: common/00menus.rpy:22 common/_compat/gamemenu.rpym:9 launcher2/archiver.rpy:170 launcher2/distribute.rpy:534 launcher2/interface.rpy:189
#, python-format
msgid "Return"
msgstr ""
#: common/00menus.rpy:24 common/_compat/gamemenu.rpym:12
#, python-format
msgid "Save Game"
msgstr ""
#: common/00menus.rpy:26 common/_compat/gamemenu.rpym:14
#, python-format
msgid "Main Menu"
msgstr ""
#: common/00menus.rpy:34 common/_compat/gamemenu.rpym:427
#, python-format
msgid "Are you sure you want to quit?"
msgstr ""
#: common/00menus.rpy:40 common/_compat/gamemenu.rpym:439
#, python-format
msgid "Are you sure you want to return to the main menu?\nThis will lose unsaved progress."
msgstr ""
#: common/_compat/gamemenu.rpym:10 common/_layout/classic_preferences.rpym:65 common/_layout/classic_preferences_common.rpym:339 common/_layout/one_column_preferences.rpym:52 common/_layout/two_column_preferences.rpym:59
#, python-format
msgid "Begin Skipping"
msgstr ""
#: common/_compat/gamemenu.rpym:177 common/_layout/classic_load_save.rpym:115 common/_layout/imagemap_load_save.rpym:95 common/_layout/scrolling_load_save.rpym:171
#, python-format
msgid "Empty Slot."
msgstr ""
#: common/_compat/gamemenu.rpym:334 common/_layout/classic_load_save.rpym:250
#, python-format
msgid "Previous"
msgstr ""
#: common/_compat/gamemenu.rpym:341 common/_layout/classic_load_save.rpym:257
#, python-format
msgid "Next"
msgstr ""
#: common/_compat/gamemenu.rpym:412 common/_layout/classic_yesno_prompt.rpym:46 launcher2/interface.rpy:223
#, python-format
msgid "Yes"
msgstr ""
#: common/_compat/gamemenu.rpym:413 common/_layout/classic_yesno_prompt.rpym:47 launcher2/interface.rpy:224
#, python-format
msgid "No"
msgstr ""
#: common/_compat/gamemenu.rpym:464 common/_layout/classic_load_save.rpym:328 common/_layout/imagemap_load_save.rpym:325 common/_layout/scrolling_load_save.rpym:214
#, python-format
msgid "Loading will lose unsaved progress.\nAre you sure you want to do this?"
msgstr ""
#: common/_compat/gamemenu.rpym:478 common/_layout/classic_load_save.rpym:314 common/_layout/imagemap_load_save.rpym:312 common/_layout/scrolling_load_save.rpym:200
#, python-format
msgid "Are you sure you want to overwrite your save?"
msgstr ""
#: common/_compat/gamemenu.rpym:494
#, python-format
msgid "The error message was:"
msgstr ""
#: common/_compat/gamemenu.rpym:496
#, python-format
msgid "You may want to try saving in a different slot, or playing for a while and trying again later."
msgstr ""
#: common/_compat/gamemenu.rpym:498
#, python-format
msgid "Save Failed."
msgstr ""
#: common/_compat/mainmenu.rpym:8
#, python-format
msgid "Continue Game"
msgstr ""
#: common/_compat/preferences.rpym:225 common/_layout/classic_preferences_common.rpym:179 common/_layout/classic_preferences_common.rpym:190 launcher2/choose_theme.rpy:228
#, python-format
msgid "Test"
msgstr ""
#: common/_compat/preferences.rpym:34 common/_layout/classic_joystick_preferences.rpym:32
#, python-format
msgid "Left"
msgstr ""
#: common/_compat/preferences.rpym:35 common/_layout/classic_joystick_preferences.rpym:33
#, python-format
msgid "Right"
msgstr ""
#: common/_compat/preferences.rpym:36 common/_layout/classic_joystick_preferences.rpym:34
#, python-format
msgid "Up"
msgstr ""
#: common/_compat/preferences.rpym:37 common/_layout/classic_joystick_preferences.rpym:35
#, python-format
msgid "Down"
msgstr ""
#: common/_compat/preferences.rpym:377 common/_compat/preferences.rpym:428 common/_layout/classic_joystick_preferences.rpym:51 common/_layout/classic_joystick_preferences.rpym:93
#, python-format
msgid "Not Assigned"
msgstr ""
#: common/_compat/preferences.rpym:38 common/_layout/classic_joystick_preferences.rpym:36
#, python-format
msgid "Select/Dismiss"
msgstr ""
#: common/_compat/preferences.rpym:39 common/_layout/classic_joystick_preferences.rpym:37
#, python-format
msgid "Rollback"
msgstr ""
#: common/_compat/preferences.rpym:40 common/_layout/classic_joystick_preferences.rpym:38
#, python-format
msgid "Hold to Skip"
msgstr ""
#: common/_compat/preferences.rpym:408 common/_layout/classic_joystick_preferences.rpym:73
#, python-format
msgid "Joystick Mapping"
msgstr ""
#: common/_compat/preferences.rpym:409 common/_layout/classic_joystick_preferences.rpym:74
#, python-format
msgid "Move the joystick or press a joystick button to create the mapping. Click the mouse to remove the mapping."
msgstr ""
#: common/_compat/preferences.rpym:41 common/_layout/classic_joystick_preferences.rpym:39
#, python-format
msgid "Toggle Skip"
msgstr ""
#: common/_compat/preferences.rpym:42 common/_layout/classic_joystick_preferences.rpym:40
#, python-format
msgid "Hide Text"
msgstr ""
#: common/_compat/preferences.rpym:43 common/_layout/classic_joystick_preferences.rpym:41
#, python-format
msgid "Menu"
msgstr ""
#: common/_compat/preferences.rpym:482 common/_compat/preferences.rpym:557 common/_layout/classic_preferences.rpym:57 common/_layout/classic_preferences_common.rpym:321 common/_layout/one_column_preferences.rpym:49 common/_layout/two_column_preferences.rpym:56 launcher2/choose_theme.rpy:208
#, python-format
msgid "Display"
msgstr ""
#: common/_compat/preferences.rpym:483 common/_layout/classic_preferences_common.rpym:322 launcher2/choose_theme.rpy:209
#, python-format
msgid "Window"
msgstr ""
#: common/_compat/preferences.rpym:484 common/_layout/classic_preferences_common.rpym:323 launcher2/choose_theme.rpy:210
#, python-format
msgid "Fullscreen"
msgstr ""
#: common/_compat/preferences.rpym:487 common/_compat/preferences.rpym:558 common/_layout/classic_preferences.rpym:58 common/_layout/classic_preferences_common.rpym:326 common/_layout/one_column_preferences.rpym:50 common/_layout/two_column_preferences.rpym:57
#, python-format
msgid "Transitions"
msgstr ""
#: common/_compat/preferences.rpym:488 common/_layout/classic_preferences_common.rpym:327
#, python-format
msgid "All"
msgstr ""
#: common/_compat/preferences.rpym:489 common/_layout/classic_preferences_common.rpym:328
#, python-format
msgid "Some"
msgstr ""
#: common/_compat/preferences.rpym:490 common/_layout/classic_preferences_common.rpym:329
#, python-format
msgid "None"
msgstr ""
#: common/_compat/preferences.rpym:495 common/_compat/preferences.rpym:563 common/_layout/classic_preferences.rpym:64 common/_layout/classic_preferences_common.rpym:334 common/_layout/one_column_preferences.rpym:51 common/_layout/two_column_preferences.rpym:58
#, python-format
msgid "Skip"
msgstr ""
#: common/_compat/preferences.rpym:496 common/_layout/classic_preferences_common.rpym:335
#, python-format
msgid "Seen Messages"
msgstr ""
#: common/_compat/preferences.rpym:497 common/_layout/classic_preferences_common.rpym:336
#, python-format
msgid "All Messages"
msgstr ""
#: common/_compat/preferences.rpym:504 common/_compat/preferences.rpym:564 common/_layout/classic_preferences.rpym:66 common/_layout/classic_preferences_common.rpym:345 common/_layout/one_column_preferences.rpym:53 common/_layout/two_column_preferences.rpym:60
#, python-format
msgid "After Choices"
msgstr ""
#: common/_compat/preferences.rpym:505 common/_layout/classic_preferences_common.rpym:346
#, python-format
msgid "Stop Skipping"
msgstr ""
#: common/_compat/preferences.rpym:506 common/_layout/classic_preferences_common.rpym:347
#, python-format
msgid "Keep Skipping"
msgstr ""
#: common/_compat/preferences.rpym:526 common/_compat/preferences.rpym:565 common/_layout/classic_preferences.rpym:59 common/_layout/classic_preferences_common.rpym:352 common/_layout/one_column_preferences.rpym:54 common/_layout/two_column_preferences.rpym:61
#, python-format
msgid "Text Speed"
msgstr ""
#: common/_compat/preferences.rpym:544 common/_compat/preferences.rpym:566 common/_layout/classic_preferences.rpym:67 common/_layout/classic_preferences_common.rpym:353 common/_layout/one_column_preferences.rpym:55 common/_layout/two_column_preferences.rpym:62
#, python-format
msgid "Auto-Forward Time"
msgstr ""
#: common/_compat/preferences.rpym:549 common/_compat/preferences.rpym:570 common/_layout/classic_preferences.rpym:71 common/_layout/classic_preferences_common.rpym:357 common/_layout/one_column_preferences.rpym:56 common/_layout/two_column_preferences.rpym:66
#, python-format
msgid "Music Volume"
msgstr ""
#: common/_compat/preferences.rpym:550 common/_compat/preferences.rpym:571 common/_layout/classic_preferences.rpym:72 common/_layout/classic_preferences_common.rpym:360 common/_layout/one_column_preferences.rpym:57 common/_layout/two_column_preferences.rpym:67
#, python-format
msgid "Sound Volume"
msgstr ""
#: common/_compat/preferences.rpym:552 common/_compat/preferences.rpym:559 common/_layout/classic_preferences.rpym:60 common/_layout/classic_preferences_common.rpym:370 common/_layout/one_column_preferences.rpym:59 common/_layout/two_column_preferences.rpym:69
#, python-format
msgid "Joystick..."
msgstr ""
#: common/_compat/preferences.rpym:554 common/_compat/preferences.rpym:575
#, python-format
msgid "Joystick Configuration"
msgstr ""
#: common/_compat/preferences.rpym:580 common/_layout/classic_preferences.rpym:73 common/_layout/classic_preferences_common.rpym:364 common/_layout/one_column_preferences.rpym:58 common/_layout/two_column_preferences.rpym:68
#, python-format
msgid "Voice Volume"
msgstr ""
#: common/_layout/classic_load_save.rpym:126
#, python-format
msgid "Auto"
msgstr ""
#: common/_layout/classic_load_save.rpym:129
#, python-format
msgid "Quick"
msgstr ""
#: launcher2/archiver.rpy:135
#, python-format
msgid "The patterns did not match any files, so no archive was created."
msgstr ""
#: launcher2/archiver.rpy:138
#, python-format
msgid "Archiving Files..."
msgstr ""
#: launcher2/archiver.rpy:165 launcher2/distribute.rpy:529
#, python-format
msgid "Success"
msgstr ""
#: launcher2/archiver.rpy:166
#, python-format
msgid "The files have been added to the archive, and moved into the \"archived\" directory. Future runs of the archiver will archive files in both the \"game\" and \"archived\" directories."
msgstr ""
#: launcher2/archiver.rpy:30
#, python-format
msgid "Archive Name:"
msgstr ""
#: launcher2/archiver.rpy:31
#, python-format
msgid "The name of the archive to create."
msgstr ""
#: launcher2/archiver.rpy:33
#, python-format
msgid "Include Patterns:"
msgstr ""
#: launcher2/archiver.rpy:34
#, python-format
msgid "Files matching these patterns are included in the archive."
msgstr ""
#: launcher2/archiver.rpy:36
#, python-format
msgid "Exclude Patterns:"
msgstr ""
#: launcher2/archiver.rpy:37
#, python-format
msgid "Files matching these patterns are excluded from the archive."
msgstr ""
#: launcher2/archiver.rpy:41
#, python-format
msgid "Archive"
msgstr ""
#: launcher2/archiver.rpy:41
#, python-format
msgid "Build the archive."
msgstr ""
#: launcher2/archiver.rpy:42 launcher2/distribute.rpy:304 launcher2/interface.rpy:159
#, python-format
msgid "Cancel"
msgstr ""
#: launcher2/archiver.rpy:50
#, python-format
msgid "Archive Name"
msgstr ""
#: launcher2/archiver.rpy:51
#, python-format
msgid "The name of the archive file to create, without the .rpa extension.\n\nThe \"data\" archive is loaded automatically. Other archives must be added to config.archives."
msgstr ""
#: launcher2/archiver.rpy:56 launcher2/archiver.rpy:62
#, python-format
msgid "Include Patterns"
msgstr ""
#: launcher2/archiver.rpy:57
#, python-format
msgid "This is a space-separated list of file patterns. Files matching these patterns are added to the archive.\n\nAsterisks (*) can be used as a wildcard."
msgstr ""
#: launcher2/archiver.rpy:63
#, python-format
msgid "This is a space-separated list of file patterns. Files matching these patterns are excluded from the archive. If a file is matched by both an exclude and include pattern, the exclude takes precedence.\n\nAsterisks (*) can be used as a wildcard."
msgstr ""
#: launcher2/archiver.rpy:98
#, python-format
msgid "Scanning Files..."
msgstr ""
#: launcher2/choose_theme.rpy:155
#, python-format
msgid "Could not modify options.rpy. Perhaps it was changed too much."
msgstr ""
#: launcher2/choose_theme.rpy:157
#, python-format
msgid "Theme changed to %s."
msgstr ""
#: launcher2/choose_theme.rpy:211
#, python-format
msgid "Planetarium"
msgstr ""
#: launcher2/choose_theme.rpy:245
#, python-format
msgid "The options.rpy file does not exist in the game directory, so this launcher cannot change the theme."
msgstr ""
#: launcher2/choose_theme.rpy:254
#, python-format
msgid "Themes control the basic look of interface elements. You'll be able to pick a color scheme next."
msgstr ""
#: launcher2/choose_theme.rpy:258 launcher2/script.rpy:45
#, python-format
msgid "Choose Theme"
msgstr ""
#: launcher2/choose_theme.rpy:296
#, python-format
msgid "Please choose a color scheme for your project."
msgstr ""
#: launcher2/choose_theme.rpy:303
#, python-format
msgid "Choose Color Scheme"
msgstr ""
#: launcher2/distribute.rpy:270
#, python-format
msgid "Base Name:"
msgstr ""
#: launcher2/distribute.rpy:271
#, python-format
msgid "Used to generate the names of directories and archive files."
msgstr ""
#: launcher2/distribute.rpy:273
#, python-format
msgid "Executable Name:"
msgstr ""
#: launcher2/distribute.rpy:274
#, python-format
msgid "Used to generate the names of executables and runnable programs."
msgstr ""
#: launcher2/distribute.rpy:276
#, python-format
msgid "Ignore Extensions:"
msgstr ""
#: launcher2/distribute.rpy:277
#, python-format
msgid "Files with these extensions will not be included in the distributions."
msgstr ""
#: launcher2/distribute.rpy:279
#, python-format
msgid "Documentation Extensions:"
msgstr ""
#: launcher2/distribute.rpy:280
#, python-format
msgid "Files with these extensions will be treated as documentation, when building the Macintosh application."
msgstr ""
#: launcher2/distribute.rpy:282
#, python-format
msgid "Distributions to Build:"
msgstr ""
#: launcher2/distribute.rpy:285
#, python-format
msgid "Windows x86"
msgstr ""
#: launcher2/distribute.rpy:286
#, python-format
msgid "Zip distribution for the 32-bit Windows platform."
msgstr ""
#: launcher2/distribute.rpy:289
#, python-format
msgid "Linux x86"
msgstr ""
#: launcher2/distribute.rpy:290
#, python-format
msgid "Tar.Bz2 distribution for the Linux x86 platform."
msgstr ""
#: launcher2/distribute.rpy:293
#, python-format
msgid "Macintosh Universal"
msgstr ""
#: launcher2/distribute.rpy:294
#, python-format
msgid "Single application distribution for the Macintosh x86 and ppc platforms."
msgstr ""
#: launcher2/distribute.rpy:297
#, python-format
msgid "Windows/Linux/Mac Combined"
msgstr ""
#: launcher2/distribute.rpy:298
#, python-format
msgid "Zip distribution for the Windows x86, Linux x86, Macintosh x86 and Macintosh ppc platforms."
msgstr ""
#: launcher2/distribute.rpy:303
#, python-format
msgid "Build"
msgstr ""
#: launcher2/distribute.rpy:303
#, python-format
msgid "Start building the distributions."
msgstr ""
#: launcher2/distribute.rpy:321
#, python-format
msgid "Base Name"
msgstr ""
#: launcher2/distribute.rpy:322
#, python-format
msgid "Please enter in the base name for your distribution. This name is used to generate the names of directories and archive files. Usually, this is the name of your game, plus a version number, like \"moonlight-1.0\"."
msgstr ""
#: launcher2/distribute.rpy:328
#, python-format
msgid "Executable Name"
msgstr ""
#: launcher2/distribute.rpy:329
#, python-format
msgid "Please enter a name for the executables in your distribution. This should not include an extension, as that will be added automatically."
msgstr ""
#: launcher2/distribute.rpy:335
#, python-format
msgid "Ignore Extensions"
msgstr ""
#: launcher2/distribute.rpy:336
#, python-format
msgid "Please enter a space-separated list of file extensions. Files with these extensions will not be included in the built distributions."
msgstr ""
#: launcher2/distribute.rpy:342
#, python-format
msgid "Documentation Extensions"
msgstr ""
#: launcher2/distribute.rpy:343
#, python-format
msgid "Please enter a space separated list of documentation extensions. Files in the base directory with these extensions will have a second copy stored outside of the Macintosh application."
msgstr ""
#: launcher2/distribute.rpy:368
#, python-format
msgid "Scanning..."
msgstr ""
#: launcher2/distribute.rpy:476
#, python-format
msgid "Building Windows..."
msgstr ""
#: launcher2/distribute.rpy:483
#, python-format
msgid "Building Linux..."
msgstr ""
#: launcher2/distribute.rpy:510
#, python-format
msgid "Building Macintosh..."
msgstr ""
#: launcher2/distribute.rpy:518
#, python-format
msgid "Building Combined..."
msgstr ""
#: launcher2/distribute.rpy:524
#, python-format
msgid "Thank you for choosing Ren'Py."
msgstr ""
#: launcher2/distribute.rpy:530
#, python-format
msgid "The distributions have been built. Be sure to test them before release.\n\nNote that unpacking and repacking the Macintosh, Linux, or Combined distributions on Windows is not supported.\n\nPlease announce your release at the {a=http://lemmasoft.renai.us/forums/}Lemma Soft Forums{/a}, so we can add it to the Ren'Py web site."
msgstr ""
#: launcher2/interface.rpy:179
#, python-format
msgid "Error"
msgstr ""
#: launcher2/interface.rpy:237
#, python-format
msgid "Press enter when done."
msgstr ""
#: launcher2/interface.rpy:255
#, python-format
msgid "The string cannot be empty. Please enter some text."
msgstr ""
#: launcher2/interface.rpy:26
#, python-format
msgid "Welcome!"
msgstr ""
#: launcher2/interface.rpy:264
#, python-format
msgid "Non-ASCII filenames are not allowed. This is because Zip files cannot reliably represent non-ASCII filenames."
msgstr ""
#: launcher2/interface.rpy:292
#, python-format
msgid "Processed %d of %d files."
msgstr ""
#: launcher2/options.rpy:26
#, python-format
msgid "%s Launcher"
msgstr ""
#: launcher2/project.rpy:173 launcher2/script.rpy:67
#, python-format
msgid "Select Project"
msgstr ""
#: launcher2/project.rpy:201
#, python-format
msgid "%s has been launched."
msgstr ""
#: launcher2/project.rpy:221
#, python-format
msgid "Opening game directory:\n%s"
msgstr ""
#: launcher2/project.rpy:244
#, python-format
msgid "No files to edit."
msgstr ""
#: launcher2/project.rpy:247
#, python-format
msgid "Launching the editor failed. You may need Java, which can be downloaded for free from {a=http://www.java.com}java.com{/a}."
msgstr ""
#: launcher2/project.rpy:249
#, python-format
msgid "Launched editor with %d script files."
msgstr ""
#: launcher2/project.rpy:282
#, python-format
msgid "Lint complete."
msgstr ""
#: launcher2/project.rpy:292
#, python-format
msgid "Deleting persistent data."
msgstr ""
#: launcher2/project.rpy:292 launcher2/script.rpy:49
#, python-format
msgid "Delete Persistent"
msgstr ""
#: launcher2/project.rpy:301
#, python-format
msgid "Persistent data has been deleted."
msgstr ""
#: launcher2/script.rpy:113
#, python-format
msgid "Now showing the Ren'Py documentation in your web browser."
msgstr ""
#: launcher2/script.rpy:28
#, python-format
msgid "Launch"
msgstr ""
#: launcher2/script.rpy:30
#, python-format
msgid "Launches the project."
msgstr ""
#: launcher2/script.rpy:32
#, python-format
msgid "Edit Script"
msgstr ""
#: launcher2/script.rpy:34
#, python-format
msgid "Edits the script of the project."
msgstr ""
#: launcher2/script.rpy:36
#, python-format
msgid "Game Directory"
msgstr ""
#: launcher2/script.rpy:38
#, python-format
msgid "Opens the project's game directory."
msgstr ""
#: launcher2/script.rpy:40
#, python-format
msgid "Check Script (Lint)"
msgstr ""
#: launcher2/script.rpy:42
#, python-format
msgid "Checks the script of the project for likely errors."
msgstr ""
#: launcher2/script.rpy:47
#, python-format
msgid "Changes the theme used by the project."
msgstr ""
#: launcher2/script.rpy:51
#, python-format
msgid "Deletes the persistent data associated with the project."
msgstr ""
#: launcher2/script.rpy:53
#, python-format
msgid "Archive Files"
msgstr ""
#: launcher2/script.rpy:55
#, python-format
msgid "Archives files found in the game and archived directories."
msgstr ""
#: launcher2/script.rpy:57
#, python-format
msgid "Build Distributions"
msgstr ""
#: launcher2/script.rpy:59
#, python-format
msgid "Builds distributions of the project."
msgstr ""
#: launcher2/script.rpy:69
#, python-format
msgid "Select a project to work with."
msgstr ""
#: launcher2/script.rpy:71
#, python-format
msgid "New Project"
msgstr ""
#: launcher2/script.rpy:73
#, python-format
msgid "Create a new project."
msgstr ""
#: launcher2/script.rpy:81
#, python-format
msgid "Project Directory"
msgstr ""
#: launcher2/script.rpy:83
#, python-format
msgid "Select the directory in which the project can be found."
msgstr ""
#: launcher2/script.rpy:85
#, python-format
msgid "Select Editor"
msgstr ""
#: launcher2/script.rpy:87
#, python-format
msgid "Select the text editor to use."
msgstr ""
#: launcher2/script.rpy:89
#, python-format
msgid "Add-ons"
msgstr ""
#: launcher2/script.rpy:91
#, python-format
msgid "Download additional components for use with Ren'Py."
msgstr ""
#: launcher2/script.rpy:93
#, python-format
msgid "Ren'Py Help"
msgstr ""
#: launcher2/script.rpy:95
#, python-format
msgid "Open the Ren'Py documentation in a web browser."
msgstr ""
+11 -2
View File
@@ -83,9 +83,18 @@ def path_to_renpy_base():
##############################################################################
# The version of the Mac Launcher and py4renpy that we require.
macos_version = (6, 10, 1)
linux_version = (6, 10, 1)
macos_version = (6, 11, 1)
linux_version = (6, 11, 1)
# Doing the version check this way also doubles as an import of ast,
# which helps py2exe et al.
try:
import ast; ast
except:
raise
print "Ren'Py requires at least python 2.6."
sys.exit(0)
if __name__ == "__main__":
if not 'RENPY_NO_VERSION_CHECK' in os.environ:
+15 -3
View File
@@ -27,17 +27,21 @@
# ***** ***** ***** ***** ***** ***** **** ***** ***** ***** *****
# Be sure to change script_version in launcher/script_version.rpy, too!
# Also check to see if we have to update renpy.py.
version = "Ren'Py 6.10.2d"
version = "Ren'Py 6.11.1b"
script_version = 5003000
savegame_suffix = "-LT1.save"
def import_all():
# True if this is the first time we've started - even including
# utter restarts.
first_utter_start = True
import renpy.game
def import_all():
# Should probably be early, as we will add it as a base to serialized things.
import renpy.object
import renpy.game
# Adds in the Ren'Py loader.
import renpy.loader
@@ -61,6 +65,7 @@ def import_all():
import renpy.display.scale # Must be before module.
import renpy.display.module
import renpy.display.render # Most display stuff depends on this.
import renpy.display.core # object
import renpy.display.font
import renpy.display.text # core, font
@@ -76,8 +81,12 @@ def import_all():
import renpy.display.particle
import renpy.display.joystick
import renpy.display.minigame
import renpy.display.screen
import renpy.display.error
import renpy.display.swdraw
import renpy.display.gldraw
# Note: For windows to work, renpy.audio.audio needs to be after
# renpy.display.module.
import renpy.audio.audio
@@ -85,6 +94,7 @@ def import_all():
import renpy.audio.sound
import renpy.ui
import renpy.screenlang
import renpy.lint
import renpy.warp
@@ -127,5 +137,7 @@ def reload_all():
import gc
gc.collect()
renpy.display.draw = None
import_all()
+60 -33
View File
@@ -82,7 +82,7 @@ class PyExpr(unicode):
__slots__ = [
'filename',
'linenumber'
'linenumber',
]
def __new__(cls, s, filename, linenumber):
@@ -104,17 +104,21 @@ class PyCode(object):
'bytecode',
]
# All PyCodes known to the system.
extent = [ ]
def __getstate__(self):
return (1, self.source, self.location, self.mode)
def __setstate__(self, state):
(_, self.source, self.location, self.mode) = state
self.bytecode = None
if renpy.game.script.record_pycode:
renpy.game.script.all_pycode.append(self)
def __init__(self, source, loc=('<none>', 1), mode='exec'):
if isinstance(source, PyExpr):
loc = (source.filename, source.linenumber, source)
# The source code.
self.source = source
@@ -126,6 +130,9 @@ class PyCode(object):
# This will be initialized later on, after we are serialized.
self.bytecode = None
if renpy.game.script.record_pycode:
renpy.game.script.all_pycode.append(self)
def chain_block(block, next):
"""
This is called to chain together all of the nodes in a block. Node
@@ -252,14 +259,6 @@ class Node(object):
else:
return [ ]
def get_pycode(self):
"""
Returns a list of PyCode objects associated with this Node,
or None if no objects are associated with it.
"""
return [ ]
def scry(self):
"""
Called to return an object with some general, user-definable information
@@ -333,6 +332,13 @@ class Say(Node):
else:
who = None
if not (
(who is None) or
callable(who) or
isinstance(who, basestring) ):
raise Exception("Sayer %s is not a function or string." % self.who.encode("utf-8"))
what = self.what
if renpy.config.say_menu_text_filter:
what = renpy.config.say_menu_text_filter(what) # E1102
@@ -373,7 +379,20 @@ class Say(Node):
def scry(self):
rv = Node.scry(self)
rv.interacts = True # W0201
if self.who is not None:
if self.who_fast:
who = getattr(renpy.store, self.who)
else:
who = renpy.python.py_eval(self.who)
else:
who = None
if self.interact:
renpy.exports.scry_say(who, rv)
else:
rv.interacts = False
return rv
# Copy the descriptor.
@@ -548,9 +567,6 @@ class Python(Node):
self.hide = hide
self.code = PyCode(python_code, loc=loc, mode='exec')
def get_pycode(self):
return [ self.code ]
def diff_info(self):
return (Python, self.code.source)
@@ -583,9 +599,6 @@ class EarlyPython(Node):
self.hide = hide
self.code = PyCode(python_code, loc=loc, mode='exec')
def get_pycode(self):
return [ self.code ]
def diff_info(self):
return (EarlyPython, self.code.source)
@@ -625,12 +638,6 @@ class Image(Node):
def diff_info(self):
return (Image, tuple(self.imgname))
def get_pycode(self):
if self.code:
return [ self.code ]
else:
return [ ]
def execute(self):
# Note: We should always check that self.code is None before
@@ -948,7 +955,7 @@ class With(Node):
return [ self.next ]
class Call(Node):
@@ -1381,12 +1388,6 @@ class Define(Node):
def diff_info(self):
return (Define, tuple(self.varname))
def get_pycode(self):
if self.code:
return [ self.code ]
else:
return [ ]
def execute(self):
value = renpy.python.py_eval_bytecode(self.code.bytecode)
@@ -1394,3 +1395,29 @@ class Define(Node):
setattr(renpy.store, self.varname, value)
return self.next
class Screen(Node):
__slots__ = [
'screen',
]
def __init__(self, loc, screen):
"""
@param name: The name of the image being defined.
@param expr: An expression yielding a Displayable that is
assigned to the image.
"""
super(Screen, self).__init__(loc)
self.screen = screen
def diff_info(self):
return (Screen, self.screen.name)
def execute(self):
self.screen.define()
return self.next
+37 -13
View File
@@ -69,6 +69,7 @@ PROPERTIES = {
"xalign" : float,
"yalign" : float,
"rotate" : float,
"rotate_pad" : bool,
"xzoom" : float,
"yzoom" : float,
"zoom" : float,
@@ -83,15 +84,22 @@ PROPERTIES = {
"corner2" : (float, float),
"subpixel" : bool,
"delay" : float,
"xoffset" : int,
"yoffset" : int,
"offset" : (int, int),
}
def correct_type(v, b, ty):
"""
Corrects the type of v to match ty. b is used to inform the match.
"""
if ty is position:
return type(b)(v)
if v is None:
return None
else:
return type(b)(v)
else:
return ty(v)
@@ -220,6 +228,11 @@ class ATLTransformBase(renpy.object.Object):
requires that t.atl is self.atl.
"""
super(ATLTransformBase, self).take_execution_state(t)
if t.atl is not self.atl:
return
self.done = t.done
self.block = t.block
self.atl_state = t.atl_state
@@ -321,10 +334,13 @@ class ATLTransformBase(renpy.object.Object):
if self.child.transform_event != self.last_child_transform_event:
self.last_child_transform_event = self.child.transform_event
self.transform_event = self.child.transform_event
# Hide request.
if trans.hide_request:
self.transform_event = "hide"
if trans.replaced_request:
self.transform_event = "replaced"
# Notice transform events.
if self.transform_event != self.last_transform_event:
@@ -339,7 +355,7 @@ class ATLTransformBase(renpy.object.Object):
timebase = at
else:
timebase = st
action, arg, pause = self.block.execute(trans, timebase, self.atl_state, event)
renpy.game.exception_info = old_exception_info
@@ -830,10 +846,10 @@ class Interpolation(Statement):
# Now, the things we change linearly are in the difference
# between the new and old states.
linear = trans.state.diff(newts)
revolution = None
splines = [ ]
# Clockwise revolution.
if self.revolution is not None:
@@ -884,12 +900,19 @@ class Interpolation(Statement):
state = (linear, revolution, splines)
# Ensure that we set things, even if they don't actually
# change from the old state.
for k, v in self.properties:
if k not in linear:
setattr(trans.state, k, v)
else:
linear, revolution, splines = state
# Linearly interpolate between the things in linear.
for k, (old, new) in linear.iteritems():
value = interpolate(complete, old, new, PROPERTIES[k])
setattr(trans.state, k, value)
# Handle the revolution.
@@ -898,6 +921,7 @@ class Interpolation(Statement):
trans.state.angle = interpolate(complete, startangle, endangle, float)
trans.state.radius = interpolate(complete, startradius, endradius, float)
# Handle any splines we might have.
for name, values in splines:
value = interpolate_spline(complete, values)
@@ -1129,7 +1153,6 @@ class On(Statement):
else:
name, start, cstate = state
# If we have an external event, and we have a handler for it,
# handle it.
if event in self.handlers:
@@ -1140,6 +1163,7 @@ class On(Statement):
name = event
start = st
cstate = None
while True:
@@ -1151,18 +1175,19 @@ class On(Statement):
# If we get a continue, save our state.
if action == "continue":
# If it comes from a hide block, indicate that.
if name == "hide":
if name == "hide" or name == "replaced":
trans.hide_response = False
trans.replaced_response = False
return "continue", (name, start, arg), pause
# If we get a next, then try going to the default
# event, unless we're already in default, in which case we
# go to None.
elif action == "next":
if name == "default" or name == "hide":
if name == "default" or name == "hide" or name == "replaced":
name = None
else:
name = "default"
@@ -1224,6 +1249,7 @@ class RawFunction(RawStatement):
compiling(self.loc)
return Function(self.loc, ctx.eval(self.expr))
class Function(Statement):
def __init__(self, loc, function):
@@ -1238,8 +1264,6 @@ class Function(Statement):
return "continue", None, fr
else:
return "next", 0, None
# This parses an ATL block.
+104 -17
View File
@@ -186,7 +186,7 @@ class Channel(object):
This stores information about the currently-playing music.
"""
def __init__(self, name, default_loop, stop_on_mute, tight):
def __init__(self, name, default_loop, stop_on_mute, tight, file_prefix, file_suffix, buffer_queue):
# The name assigned to this channel. This is used to look up
# information about the channel in the MusicContext object.
@@ -250,6 +250,12 @@ class Channel(object):
# on queue clear.
self.keep_queue = 0
# A prefix and suffix that are used to create the full filenames.
self.file_prefix = file_prefix
self.file_suffix = file_suffix
# Should we buffer upcoming music/video in the queue?
self.buffer_queue = buffer_queue
if default_loop is None:
# By default, should we loop the music?
@@ -340,6 +346,11 @@ class Channel(object):
if depth >= 2:
break
# If we can't buffer things, and we're playing something
# give up here.
if not self.buffer_queue and depth >= 1:
break
# We can't queue anything if the depth is > 0 and we're
# waiting for a synchro_start.
if self.synchro_start and depth:
@@ -354,7 +365,7 @@ class Channel(object):
# Blacklist of old file formats we used to support, but we now
# ignore.
lfn = topq.filename.lower()
lfn = topq.filename.lower() + self.file_suffix.lower()
for i in (".mod", ".xm", ".mid", ".midi"):
if lfn.endswith(i):
topq = None
@@ -363,7 +374,7 @@ class Channel(object):
continue
try:
topf = load(topq.filename)
topf = load(self.file_prefix + topq.filename + self.file_suffix)
if depth == 0:
pss.play(self.number, topf, topq.filename, paused=self.synchro_start, fadein=topq.fadein, tight=topq.tight)
@@ -457,7 +468,6 @@ class Channel(object):
else:
pss.fadeout(self.number, int(secs * 1000))
def enqueue(self, filenames, loop=True, synchro_start=False, fadein=0, tight=None):
for filename in filenames:
@@ -491,8 +501,19 @@ class Channel(object):
if not pcm_ok:
return None
return pss.playing_name(self.number)
rv = pss.playing_name(self.number)
if rv is None and self.queue:
rv = self.queue[0].filename
if rv is None and self.loop:
rv = self.loop[0]
return rv
def set_volume(self, volume):
self.chan_volume = volume
@@ -528,14 +549,52 @@ all_channels = [ ]
channels = { }
def register_channel(name, mixer=None, loop=None, stop_on_mute=True, tight=False):
def register_channel(name, mixer=None, loop=None, stop_on_mute=True, tight=False, file_prefix="", file_suffix="", buffer_queue=False):
"""
:doc: other
This registers a new audio channel named `name`. Audio can then be
played on the channel by supplying the channel name to the play or
queue statements.
`mixer`
The name of the mixer the channel uses. By default, Ren'Py
knows about the "music", "sfx", and "voice" mixers. Using
other names is possible, but may require changing the
preferences screens.
`loop`
If true, sounds on this channel loop by default.
`stop_on_mute`
If true, music on the channel is stopped when the channel is muted.
`tight`
If true, sounds will loop even when fadeout is occuring. This should
be set to True for a sound effects or seamless music channel, and False
if the music fades out on its own.
`file_prefix`
A prefix that is prepended to the filenames of the sound files being
played on this channel.
`file_suffix`
A suffix that is appended to the filenames of the sound files being
played on this channel.
`buffer_queue`
Should we buffer the first second or so of a queued file? This should
be True for audio, and False for movie playback.
"""
if not renpy.game.init_phase:
raise Exception("Can't register channel outside of init phase.")
c = Channel(name, loop, stop_on_mute, tight)
c = Channel(name, loop, stop_on_mute, tight, file_prefix, file_suffix, buffer_queue)
c.mixer = mixer
all_channels.append(c)
channels[name] = c
def alias_channel(name, newname):
if not renpy.game.init_phase:
@@ -543,6 +602,7 @@ def alias_channel(name, newname):
c = get_channel(name)
channels[newname] = c
def get_channel(name):
@@ -672,7 +732,7 @@ def periodic():
anything_playing = False
for c in channels:
for c in all_channels:
vol = c.chan_volume * volumes[c.mixer]
max_volume = max(max_volume, vol)
@@ -759,10 +819,37 @@ def interact():
periodic()
def rollback():
"""
On rollback, we want to stop all the channels with non-empty sounds.
"""
for c in all_channels:
if not c.loop:
c.fadeout(0)
ALLOC_EVENT = pygame.USEREVENT
REFRESH_EVENT = pygame.USEREVENT + 1
# The last surface we allocated.
last_alloc_surface = None
def alloc_surface(force):
global last_alloc_surface
if renpy.display.video.fullscreen and renpy.display.draw.fullscreen_surface:
surf = renpy.display.draw.fullscreen_surface
else:
surf = renpy.display.video.surface
if (surf is not last_alloc_surface) or force:
last_alloc_surface = surf
pss.alloc_event(surf)
def event(ev):
"""
Handles an event generated by pss (really, the ffdecode
@@ -773,21 +860,21 @@ def event(ev):
if not pcm_ok:
return False
if ev.type == ALLOC_EVENT:
if renpy.display.video.fullscreen or not renpy.display.video.surface:
surf = pygame.display.get_surface()
else:
surf = renpy.display.video.surface
pss.alloc_event(renpy.display.scale.real(surf))
alloc_surface(True)
return True
if ev.type == REFRESH_EVENT:
elif ev.type == REFRESH_EVENT:
alloc_surface(False)
if renpy.audio.music.get_playing("movie"):
pss.refresh_event()
renpy.game.interface.force_redraw = True
# Return False, as a Movie should get this to know when to
# redraw itself.
return False
+11
View File
@@ -169,6 +169,17 @@ def queue(filenames, channel="music", loop=None, clear_queue=True, fadein=0, tig
if renpy.config.debug_sound:
raise
def playable(filename, channel="music"):
"""
Return true if the given filename is playable on the channel. This
takes into account the prefix and suffix.
"""
c = get_channel(channel)
return renpy.loader.loadable(c.file_prefix + filename + c.file_suffix)
def stop(channel="music", fadeout=None):
"""
This stops the music that is currently playing, and dequeues all
-2
View File
@@ -37,8 +37,6 @@ def play(filename, channel="sound", fadeout=0, fadein=0, tight=False, loop=False
fadein=fadein,
tight=tight,
loop=loop)
def queue(filename, channel="sound", clear_queue=True, fadein=0, tight=False, loop=False):
renpy.audio.music.queue(filename,
+70 -60
View File
@@ -58,6 +58,12 @@ def extra_imports():
import ctypes
import ctypes.wintypes; ctypes.wintypes
import EasyDialogs; EasyDialogs
import argparse; argparse
import compiler; compiler
import textwrap; textwrap
import copy; copy
import urllib; urllib
import urllib2; urllib2
trace_file = None
trace_local = None
@@ -84,18 +90,9 @@ def mac_start(fn):
os.system("open " + fn)
# This code fixes a bug in subprocess.Popen.__del__
def popen_del(self, _deadstate=sys.maxint):
if not self._child_created:
return
self.poll(_deadstate=_deadstate)
def popen_del(self, *args, **kwargs):
return
try:
import subprocess # W0403
if self.returncode is None and subprocess._active is not None: # E1101
subprocess._active.append(self) # E1101
except:
pass
def bootstrap(renpy_base):
global renpy # W0602
@@ -229,10 +226,6 @@ def bootstrap(renpy_base):
import renpy.display.presplash # W0404
renpy.display.presplash.start(gamedir)
# Fix an exception thrown by garbage collection.
import subprocess # W0403
subprocess.Popen.__del__ = popen_del # E1101
# If we're on a mac, install our own os.start.
if sys.platform == "darwin":
os.startfile = mac_start
@@ -248,55 +241,73 @@ def bootstrap(renpy_base):
keep_running = True
report_error = None
while keep_running:
try:
renpy.game.options = options
try:
while keep_running:
try:
renpy.game.options = options
renpy.config.renpy_base = renpy_base
renpy.config.basedir = basedir
renpy.config.gamedir = gamedir
renpy.config.args = options.args
renpy.main.main()
keep_running = False
renpy.config.renpy_base = renpy_base
renpy.config.basedir = basedir
renpy.config.gamedir = gamedir
renpy.config.args = options.args
except KeyboardInterrupt:
import traceback
traceback.print_exc()
break
except renpy.game.UtterRestartException:
# Only works after a full restart.
report_error = renpy.display.error.ReportError()
# On an UtterRestart, reload Ren'Py.
renpy.reload_all()
continue
except renpy.game.ParseErrorException:
if report_error and report_error.report('a parse error'):
renpy.reload_all()
keep_running = True
else:
renpy.main.main()
keep_running = False
except KeyboardInterrupt:
import traceback
traceback.print_exc()
break
except renpy.game.UtterRestartException:
if renpy.display.draw:
renpy.display.draw.deinit()
renpy.display.draw.quit()
# Only works after a full restart.
report_error = renpy.display.error.ReportError()
# On an UtterRestart, reload Ren'Py.
renpy.reload_all()
continue
except renpy.game.ParseErrorException:
if report_error and report_error.report('a parse error'):
renpy.reload_all()
keep_running = True
else:
keep_running = False
except Exception, e:
report_exception(e)
if report_error and report_error.report('an exception'):
renpy.reload_all()
keep_running = True
else:
keep_running = False
sys.exit(0)
finally:
except Exception, e:
report_exception(e)
if "RENPY_SHUTDOWN_TRACE" in os.environ:
enable_trace(int(os.environ["RENPY_SHUTDOWN_TRACE"]))
if report_error and report_error.report('an exception'):
renpy.reload_all()
keep_running = True
else:
keep_running = False
if options.leak:
memory_profile()
renpy.display.im.cache.quit()
renpy.display.im.cache.quit()
sys.exit(0)
if renpy.display.draw:
renpy.display.draw.quit()
# Prevent subprocess from throwing errors while trying to run it's
# __del__ method during shutdown.
import subprocess # W0403
subprocess.Popen.__del__ = popen_del # E1101
if options.leak:
memory_profile()
def report_tb(out, tb):
@@ -354,8 +365,7 @@ def report_exception(e):
f.write(codecs.BOM_UTF8)
print >>f, "I'm sorry, but an exception occured while executing your Ren'Py"
print >>f, "script."
print >>f, "I'm sorry, but an uncaught exception occurred."
print >>f
print >>f, type.__name__ + ":",
+196 -75
View File
@@ -22,6 +22,79 @@
# The Character object (and friends).
import renpy
import re
# This matches the dialogue-relevant text tags.
TAG_RE = re.compile(r'(\{\{)|(\{(p|w|nw|fast)(?:\=([^}]*))?\})', re.S)
class DialogueTextTags(object):
"""
This object parses the text tags that only make sense in dialogue,
like {fast}, {p}, {w}, and {nw}.
"""
def __init__(self, s):
# The text that we've accumulated, not including any tags.
self.text = ""
# The index in the produced string where each pause starts.
self.pause_start = [ 0 ]
# The index in the produced string where each pause ends.
self.pause_end = [ ]
# The time to delay for each pause. None to delay forever.
self.pause_delay = [ ]
# True if we've encountered the no-wait tag.
self.no_wait = False
i = iter(TAG_RE.split(s))
while True:
try:
self.text += i.next()
quoted = i.next()
full_tag = i.next()
tag = i.next()
value = i.next()
if value is not None:
value = float(value)
if quoted is not None:
self.text += quoted
continue
if tag == "p" or tag == "w":
self.pause_start.append(len(self.text))
self.pause_end.append(len(self.text))
self.pause_delay.append(value)
elif tag == "nw":
self.no_wait = True
elif tag == "fast":
self.pause_start = [ len(self.text) ]
self.pause_end = [ ]
self.pause_delay = [ ]
self.no_wait = False
self.text += full_tag
except StopIteration:
break
self.pause_end.append(len(self.text))
if self.no_wait:
self.pause_delay.append(0)
else:
self.pause_delay.append(None)
def predict_show_display_say(who, what, who_args, what_args, window_args, image=False, two_window=False, side_image=None, **kwargs):
"""
@@ -57,6 +130,7 @@ def show_display_say(who, what, who_args={}, what_args={}, window_args={},
say_vbox_properties={},
transform=None,
variant=None,
screen=None,
**kwargs):
"""
This is called (by default) by renpy.display_say to add the
@@ -144,6 +218,33 @@ def show_display_say(who, what, who_args={}, what_args={}, window_args={},
what_args = style_args(what_args)
window_args = style_args(window_args)
if screen and renpy.display.screen.has_screen(screen):
widget_properties = {
"window" : window_args,
"what" : what_args,
"who" : who_args,
}
tag = screen
index = 0
while renpy.exports.showing(tag):
index += 1
tag = "%s%d" % (screen, index)
renpy.display.screen.show_screen(
screen,
_widget_properties=widget_properties,
_transient = True,
_tag = tag,
who=who,
what=what)
renpy.exports.shown_window()
return renpy.display.screen.get_widget(screen, "what")
# Apply the transform.
if transform:
renpy.ui.at(transform)
@@ -182,47 +283,56 @@ def show_display_say(who, what, who_args={}, what_args={}, window_args={},
class SlowDone(object):
def __init__(self, ctc, ctc_position, callback, interact, type, cb_args):
delay = None
def __init__(self, ctc, ctc_position, callback, interact, type, cb_args, delay):
self.ctc = ctc
self.ctc_position = ctc_position
self.callback = callback
self.interact = interact
self.type = type
self.cb_args = cb_args
self.delay = delay
def __call__(self):
if self.ctc and self.ctc_position == "fixed":
renpy.ui.add(self.ctc)
renpy.display.screen.show_screen("_ctc", _transient=True, ctc=self.ctc)
renpy.exports.restart_interaction()
if self.delay is not None:
renpy.ui.pausebehavior(self.delay, True)
renpy.exports.restart_interaction()
for c in self.callback:
c("slow_done", interact=self.interact, type=self.type, **self.cb_args)
# This function takes care of repeatably showing the screen as part of
# an interaction.
def display_say(show_function,
interact,
slow,
afm,
ctc,
ctc_pause,
ctc_position,
all_at_once,
cb_args,
with_none,
callback,
type,
checkpoint=True,
ctc_timedpause=None,
ctc_force=False):
def display_say(
who,
what,
show_function,
interact,
slow,
afm,
ctc,
ctc_pause,
ctc_position,
all_at_once,
cb_args,
with_none,
callback,
type,
checkpoint=True,
ctc_timedpause=None,
ctc_force=False):
# If we're in fast skipping mode, don't bother with say
# statements at all.
if interact and renpy.config.skipping == "fast":
# Clears out transients.
renpy.exports.with_statement(None)
return
@@ -238,7 +348,6 @@ def display_say(show_function,
callback = [ callback ]
callback = renpy.config.all_character_callbacks + callback
# Call the begin callback.
for c in callback:
@@ -260,44 +369,54 @@ def display_say(show_function,
renpy.game.context().seen_current(True))):
slow = False
# Figure out which pause we're on. (Or set the pause to None in
# order to put us in all-at-once mode.)
if not interact:
all_at_once = True
dtt = DialogueTextTags(what)
if all_at_once:
pause = None
pause_start = [ dtt.pause_start[0] ]
pause_end = [ len(dtt.text) ]
pause_delay = [ dtt.pause_delay[-1] ]
else:
pause = 0
pause_start = dtt.pause_start
pause_end = dtt.pause_end
pause_delay = dtt.pause_delay
# True if the {nw} tag was found in what_text.
no_wait = False
keep_interacting = True
slow_start = 0
while keep_interacting:
for i, (start, end, delay) in enumerate(zip(pause_start, pause_end, pause_delay)):
last_pause = (i == len(pause_start) - 1)
# If we're going to do an interaction, then saybehavior needs
# to be here.
if interact:
behavior = renpy.ui.saybehavior(allow_dismiss=renpy.config.say_allow_dismiss)
behavior = renpy.ui.saybehavior(allow_dismiss=renpy.config.say_allow_dismiss)
else:
behavior = None
# Run the show callback.
for c in callback:
c("show", interact=interact, type=type, **cb_args)
what_text = show_function()
# Show the text.
what_text = show_function(who, dtt.text)
if not isinstance(what_text, renpy.display.text.Text):
raise Exception("The say screen (or show_function) must return a Text object.")
# Update the properties of the what_text widget.
if pause is not None and pause < what_text.pauses:
if what_text.pause_lengths[pause] is not None:
if last_pause:
what_ctc = ctc
else:
if delay is not None:
what_ctc = ctc_timedpause or ctc_pause
else:
what_ctc = ctc_pause
else:
what_ctc = ctc
if not (interact or ctc_force):
what_ctc = None
@@ -306,35 +425,28 @@ def display_say(show_function,
if what_ctc is not None:
what_ctc = what_ctc.parameterize(('ctc',), ())
if delay == 0:
what_ctc = None
# This object is called when the slow text is done.
slow_done = SlowDone(what_ctc, ctc_position, callback, interact, type, cb_args)
slow_done = SlowDone(what_ctc, ctc_position, callback, interact, type, cb_args, delay)
what_text.slow = slow
what_text.slow_param = slow
what_text.slow_done = slow_done
what_text.slow_start = slow_start
what_text.pause = pause
what_text.slow_start = start
what_text.slow_end = end
if what_ctc and ctc_position == "nestled":
what_text.tokens.append([ ("widget", what_ctc) ])
what_text.set_ctc(what_ctc)
# Now, re-run update on what_text.
what_text.update(retokenize=False)
keep_interacting = what_text.keep_pausing
no_wait |= what_text.no_wait
if no_wait:
slow_done.ctc = None
for c in callback:
c("show_done", interact=interact, type=type, **cb_args)
if behavior and afm:
behavior.set_afm_length(what_text.get_simple_length() - slow_start) # E1103
behavior.set_afm_length(end - start)
if interact:
if interact:
rv = renpy.ui.interact(mouse='say', type=type, roll_forward=roll_forward)
# This is only the case if the user has rolled forward, {nw} happens, or
@@ -342,18 +454,14 @@ def display_say(show_function,
if rv is False:
break
slow_start = what_text.get_laidout_length()
if keep_interacting:
pause += 1
for i in renpy.config.say_sustain_callbacks:
i()
if not last_pause:
for i in renpy.config.say_sustain_callbacks:
i()
# Do the checkpoint and with None.
if interact:
if not no_wait:
if not dtt.no_wait:
if checkpoint:
renpy.exports.checkpoint(True)
else:
@@ -431,8 +539,9 @@ class ADVCharacter(object):
self.condition = v('condition')
self.dynamic = v('dynamic')
self.screen = v('screen')
self.mode = v('mode')
self.display_args = dict(
interact = d('interact'),
slow = d('slow'),
@@ -445,7 +554,7 @@ class ADVCharacter(object):
with_none = d('with_none'),
callback = d('callback'),
type = d('type'),
)
)
if kind:
self.who_args = kind.who_args.copy()
@@ -493,13 +602,11 @@ class ADVCharacter(object):
def copy(self, name=NotSet, **properties):
return type(self)(name, kind=self, **properties)
# This is called before the interaction.
def do_add(self, who, what):
return
# A curried version of this is called to cause the interaction to
# occur.
# This is what shows the screen for a given interaction.
def do_show(self, who, what):
return self.show_function(
who,
@@ -507,6 +614,7 @@ class ADVCharacter(object):
who_args=self.who_args,
what_args=self.what_args,
window_args=self.window_args,
screen=self.screen,
**self.show_args)
# This is called after the last interaction is done.
@@ -519,8 +627,10 @@ class ADVCharacter(object):
return
# This is called to actually do the displaying.
def do_display(self, who, what, **display_args):
display_say(lambda : self.do_show(who, what),
def do_display(self, who, what, **display_args):
display_say(who,
what,
self.do_show,
**display_args)
@@ -535,17 +645,21 @@ class ADVCharacter(object):
window_args=self.window_args,
**self.show_args)
def __call__(self, what, **kwargs):
def __call__(self, what, interact=True, **kwargs):
# Check self.condition to see if we should show this line at all.
if not (self.condition is None or renpy.python.py_eval(self.condition)):
return True
if interact:
renpy.exports.mode(self.mode)
# Figure out the arguments to display.
display_args = self.display_args.copy()
display_args.update(kwargs)
display_args["interact"] = display_args["interact"] and interact
who = self.name
# If dynamic is set, evaluate the name expression.
@@ -572,8 +686,7 @@ class ADVCharacter(object):
renpy.exports.log(who)
renpy.exports.log(what)
renpy.exports.log("")
def predict(self, what):
if self.dynamic:
@@ -582,14 +695,22 @@ class ADVCharacter(object):
who = self.name
return self.do_predict(who, what)
def will_interact(self):
if not (self.condition is None or renpy.python.py_eval(self.condition)):
return False
return self.display_args['interact']
def Character(name=NotSet, kind=None, **properties):
if kind is None:
kind = renpy.store.adv
return type(kind)(name, kind=kind, **properties)
def DynamicCharacter(name_expr, **properties):
return Character(name_expr, dynamic=True, **properties)
+27 -3
View File
@@ -132,7 +132,7 @@ fade_music = 0.0
sticky_positions = False
# A list of all of the layers that we know about.
layers = [ 'master', 'transient', 'overlay' ]
layers = [ 'master', 'transient', 'screens', 'overlay' ]
# A list of layers that should be cleared when we replace
# transients.
@@ -142,6 +142,10 @@ transient_layers = [ 'transient' ]
# overlays.
overlay_layers = [ 'overlay' ]
# A list of layers that should be cleared whe we enter a
# new context.
context_clear_layers = [ 'screens' ]
# A list of layers that are displayed atop all other layers, and do
# not participate in transitions.
top_layers = [ ]
@@ -168,7 +172,7 @@ keymap = dict(
# disabled.
rollback = [ 'K_PAGEUP', 'mousedown_4', 'joy_rollback' ],
screenshot = [ 's' ],
toggle_fullscreen = [ 'f', 'alt_K_RETURN', 'alt_K_KP_ENTER' ],
toggle_fullscreen = [ 'f', 'alt_K_RETURN', 'alt_K_KP_ENTER', 'K_F11' ],
toggle_music = [ 'm' ],
game_menu = [ 'K_ESCAPE', 'mouseup_3', 'joy_menu' ],
hide_windows = [ 'mouseup_2', 'h', 'joy_hide' ],
@@ -343,7 +347,7 @@ all_character_callbacks = [ ]
autosave_slots = 10
# How often do we autosave. (Number of interactions, sort of.)
autosave_frequency = 200
autosave_frequency = int(os.environ.get("RENPY_AUTOSAVE_FREQUENCY", "200"))
# The callback that is used by the scene statement.
scene = renpy.exports.scene
@@ -412,12 +416,32 @@ end_game_transition = None
# The default transform.
default_transform = None
# Should we use the child position?
transform_uses_child_position = True
# The action to use when it's time to quit.
quit_action = None
# If not None, a rectangle giving the area of the screen to crop the
# screenshots to.
screenshot_crop = None
# Various directories.
gamedir = None
basedir = None
renpy_base = None
# Should we enable OpenGL mode?
gl_enable = True
# A list of callbacks that are called by renpy.mode.
mode_callbacks = [ ]
# Should MoveTransition take offsets into account?
movetransition_respects_offsets = True
del renpy
del os
def init():
import renpy # W0404
+7 -4
View File
@@ -26,13 +26,13 @@ class Curry(object):
supplied to the call.
"""
# __doc__ = property(fget=lambda self : self.callable.__doc__)
def __init__(self, callable, *args, **kwargs):
self.callable = callable
self.args = args
self.kwargs = kwargs
self.__doc__ = getattr(self.callable, "__doc__", None)
def __call__(self, *args, **kwargs):
return self.callable(*(self.args + args),
**dict(self.kwargs.items() + kwargs.items()))
@@ -58,8 +58,11 @@ def curry(fn):
same thing as the function called once.
"""
return Curry(Curry, fn)
rv = Curry(Curry, fn)
rv.__doc__ = getattr(fn, "__doc__", None)
return rv
def partial(function, *args, **kwargs):
"""
Stores the arguments and keyword arguments of function, and
+18 -1
View File
@@ -19,4 +19,21 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file intentionally left blank.
# The draw object through which all drawing is routed. This object
# contains all of the distinction between the software and GL
# renderers.
draw = None
# The interface object.
interface = None
# The old OpenGL physical size. Used to restore things after a reload.
# (Stashed here since this module doesn't get reloaded.)
gl_size = None
# Should we give up on opengl? This is controlled by shift on initial
# start.
gl_giveup = None
# The renderers we prefer to use.
prefer_renderers = "gl,sw"
+294 -52
View File
@@ -161,14 +161,82 @@ def inspector(ev):
return map_event(ev, "inspector")
##############################################################################
# Utility functions for dealing with actions.
def run(var, *args, **kwargs):
"""
Runs a variable. This is done by calling all the functions, and
iterating over the lists and tuples.
"""
if var is None:
return None
if isinstance(var, (list, tuple)):
rv = None
for i in var:
new_rv = i(*args)
if new_rv is not None:
rv = new_rv
return rv
return var(*args)
def run_periodic(var, st):
if isinstance(var, (list, tuple)):
rv = None
for i in var:
v = run_periodic(i, st)
if rv is None or v < rv:
rv = v
return rv
if isinstance(var, renpy.ui.Action):
return var.periodic(st)
def is_selected(clicked):
if isinstance(clicked, (list, tuple)):
return any(is_selected(i) for i in clicked)
elif isinstance(clicked, renpy.ui.Action):
return clicked.get_selected()
else:
return False
def is_sensitive(clicked):
if isinstance(clicked, (list, tuple)):
return all(is_sensitive(i) for i in clicked)
elif isinstance(clicked, renpy.ui.Action):
return clicked.get_sensitive()
else:
return True
##############################################################################
# Special-Purpose Displayables
class Keymap(renpy.display.layout.Null):
"""
This is a behavior that maps keys to functions that are called when
This is a behavior that maps keys to actions that are called when
the key is pressed. The keys are specified by giving the appropriate
k_constant from pygame.constants, or the unicode for the key.
"""
def __init__(self, **keymap):
def __init__(self, replaces=None, **keymap):
super(Keymap, self).__init__(style='default')
self.keymap = keymap
@@ -176,7 +244,8 @@ class Keymap(renpy.display.layout.Null):
for name, action in self.keymap.iteritems():
if map_event(ev, name):
rv = action()
rv = run(action)
if rv is not None:
return rv
@@ -189,8 +258,8 @@ class RollForward(renpy.display.layout.Null):
This behavior implements rollforward.
"""
def __init__(self, value):
super(RollForward, self).__init__(style='default')
def __init__(self, value, **properties):
super(RollForward, self).__init__(**properties)
self.value = value
@@ -202,25 +271,33 @@ class RollForward(renpy.display.layout.Null):
renpy.game.log.rolled_forward = True
return self.value
class PauseBehavior(renpy.display.layout.Null):
"""
This is a class implementing the Pause behavior, which is to
return a value after a certain amount of time has elapsed.
"""
def __init__(self, delay, result=False):
super(PauseBehavior, self).__init__()
def __init__(self, delay, result=False, **properties):
super(PauseBehavior, self).__init__(**properties)
self.delay = delay
self.result = result
def event(self, ev, x, y, st):
if self.delay is not None and st >= self.delay:
return self.result
if st >= self.delay:
renpy.game.interface.timeout(self.delay - st)
# If we have been drawn since the timeout, simply return
# true. Otherwise, force a redraw, and return true when
# it comes back.
if renpy.game.interface.drawn_since(st - self.delay):
return self.result
else:
renpy.game.interface.force_redraw = True
renpy.game.interface.timeout(max(self.delay - st, 0))
class SoundStopBehavior(renpy.display.layout.Null):
"""
@@ -229,8 +306,8 @@ class SoundStopBehavior(renpy.display.layout.Null):
on the named channel.
"""
def __init__(self, channel, result=False):
super(SoundStopBehavior, self).__init__()
def __init__(self, channel, result=False, **properties):
super(SoundStopBehavior, self).__init__(**properties)
self.channel = channel
self.result = result
@@ -243,6 +320,7 @@ class SoundStopBehavior(renpy.display.layout.Null):
renpy.game.interface.timeout(.025)
class SayBehavior(renpy.display.layout.Null):
"""
This is a class that implements the say behavior,
@@ -270,7 +348,7 @@ class SayBehavior(renpy.display.layout.Null):
self.allow_dismiss = allow_dismiss
def set_afm_length(self, afm_length):
self.afm_length = afm_length
self.afm_length = max(afm_length, 1)
def event(self, ev, x, y, st):
@@ -301,6 +379,11 @@ class SayBehavior(renpy.display.layout.Null):
renpy.exports.restart_interaction()
raise renpy.display.core.IgnoreEvent()
if renpy.game.preferences.using_afm_enable and renpy.game.preferences.afm_enable:
renpy.game.preferences.afm_enable = False
renpy.exports.restart_interaction()
raise renpy.display.core.IgnoreEvent()
if self.allow_dismiss:
if not self.allow_dismiss():
raise renpy.display.core.IgnoreEvent()
@@ -326,18 +409,41 @@ class SayBehavior(renpy.display.layout.Null):
return None
##############################################################################
# Button
class Button(renpy.display.layout.Window):
keymap = { }
action = None
def __init__(self, child, style='button', clicked=None,
hovered=None, unhovered=None, role='',
def __init__(self, child=None, style='button', clicked=None,
hovered=None, unhovered=None, action=None, role=None,
time_policy=None, keymap={},
**properties):
super(Button, self).__init__(child, style=style, **properties)
if isinstance(clicked, renpy.ui.Action):
action = clicked
if action is not None:
clicked = action
if not is_sensitive(action):
clicked = None
if role is None:
if action:
if is_selected(action):
role = 'selected_'
else:
role = ''
else:
role = ''
self.action = action
self.activated = False
self.clicked = clicked
self.hovered = hovered
@@ -347,7 +453,7 @@ class Button(renpy.display.layout.Window):
self.keymap = keymap
self.time_policy_data = None
def render(self, width, height, st, at):
@@ -396,9 +502,9 @@ class Button(renpy.display.layout.Window):
return None
rv = None
if self.hovered and not default:
rv = self.hovered()
if not default:
rv = run(self.hovered)
self.set_transform_event(self.role + "hover")
self.child.set_transform_event(self.role + "hover")
@@ -406,14 +512,14 @@ class Button(renpy.display.layout.Window):
return rv
def unfocus(self):
def unfocus(self, default=False):
super(Button, self).unfocus()
if self.activated:
return None
if self.unhovered:
self.unhovered()
if not default:
run(self.unhovered)
self.set_transform_event(self.role + "idle")
self.child.set_transform_event(self.role + "idle")
@@ -422,11 +528,19 @@ class Button(renpy.display.layout.Window):
def per_interact(self):
if not self.clicked:
self.set_style_prefix(self.role + "insensitive_", True)
else:
self.set_style_prefix(self.role + "idle_", True)
super(Button, self).per_interact()
def event(self, ev, x, y, st):
# Call self.action.periodic()
timeout = run_periodic(self.action, st)
if timeout is not None:
renpy.game.interface.timeout(timeout)
# If we have a child, try passing the event to it.
rv = super(Button, self).event(ev, x, y, st)
if rv is not None:
@@ -439,10 +553,7 @@ class Button(renpy.display.layout.Window):
# Check the keymap.
for name, action in self.keymap.iteritems():
if map_event(ev, name):
rv = action()
if rv is not None:
return rv
return run(action)
# Ignore as appropriate:
if map_event(ev, "button_ignore") and self.clicked:
@@ -457,7 +568,7 @@ class Button(renpy.display.layout.Window):
if self.style.sound:
renpy.audio.music.play(self.style.sound, channel="sound")
rv = self.clicked()
rv = run(self.clicked)
if rv is not None:
return rv
@@ -509,17 +620,20 @@ class Input(renpy.display.text.Text):
prefix = ""
suffix = ""
def __init__(self, default, length=None,
style='input_text',
def __init__(self,
default="",
length=None,
style='input',
allow=None,
exclude=None,
prefix="",
suffix="",
changed=None,
button=None,
replaces=None,
**properties):
super(Input, self).__init__("", style=style, **properties)
super(Input, self).__init__("", style=style, replaces=replaces, **properties)
self.content = unicode(default)
self.length = length
@@ -544,9 +658,14 @@ class Input(renpy.display.text.Text):
self.editable = False
button.hovered = HoveredProxy(self.enable, button.hovered)
button.unhovered = HoveredProxy(self.disable, button.unhovered)
if isinstance(replaces, Input):
self.content = replaces.content
self.editable = replaces.editable
self.update_text(self.content, self.editable)
def update_text(self, content, editable):
if content != self.content or editable != self.editable:
@@ -614,16 +733,80 @@ adj_registered = { }
# This class contains information about an adjustment that can change the
# position of content.
class Adjustment(renpy.object.Object):
"""
:doc: ui
:name: ui.adjustment class
Adjustment objects represent a value that can be adjusted by a bar
or viewport. They contain information about the value, the range
of the value, and how to adjust the value in small steps and large
pages.
"""
def __init__(self, range=1, value=0, step=None, page=0, changed=None, adjustable=None, ranged=None):
"""
The following parameters correspond to fields or properties on
the adjustment object:
`range`
The range of the adjustment, a number.
`value`
The value of the adjustment, a number.
`step`
The step size of the adjustment, a number. If None, then
defaults to 1/10th of a page, if set. Otherwise, defaults
to the 1/20th of the range.
This is used when scrolling a viewport with the mouse wheel.
`page`
The page size of the adjustment. If None, this is set
automatically by a viewport. If never set, defaults to 1/10th
of the range.
It's can be used when clicking on a scrollbar.
The following parameters control the behavior of the adjustment.
`adjustable`
If True, this adjustment can be changed by a bar. If False,
it can't.
It defaults to being adjustable if a `changed` function
is given or if the adjustment is associated with a viewport,
and not adjustable otherwise.
`changed`
This function is called with the new value when the value of
the adjustment changes.
`ranged`
This function is called with the adjustment object when
the range of the adjustment is set by a viewport.
.. method:: change(value)
Changes the value of the adjustment to `value`, updating
any bars and viewports that use the adjustment.
"""
def __init__(self, range=1, value=0, step=None, page=0, changed=None, adjustable=True, ranged=None):
super(Adjustment, self).__init__()
if adjustable is None:
if changed:
adjustable = True
self._value = value
self._range = range
self._page = page
self._step = step
self.changed = changed
self.adjustable = changed or adjustable
self.adjustable = adjustable
self.ranged = ranged
def get_value(self):
@@ -698,8 +881,8 @@ class Bar(renpy.display.core.Displayable):
to clicks on that value.
"""
__version__ = 1
__version__ = 2
def after_upgrade(self, version):
if version < 1:
@@ -708,7 +891,10 @@ class Bar(renpy.display.core.Displayable):
del self.range # E1101
del self.value # E1101
del self.changed # E1101
if version < 2:
self.value = None
def __init__(self,
range=None,
value=None,
@@ -719,12 +905,37 @@ class Bar(renpy.display.core.Displayable):
step=None,
page=None,
bar=None,
style='bar',
style=None,
vertical=False,
replaces=None,
**properties):
if adjustment is None:
adjustment = Adjustment(range, value, step=step, page=page, changed=changed, adjustable=False)
self.value = None
if adjustment is None:
if isinstance(value, renpy.ui.BarValue):
if isinstance(replaces, Bar):
value.replaces(replaces.value)
self.value = value
adjustment = value.get_adjustment()
renpy.game.interface.timeout(0)
else:
adjustment = Adjustment(range, value, step=step, page=page, changed=changed)
if style is None:
if self.value is not None:
if vertical:
style = self.value.get_style()[1]
else:
style = self.value.get_style()[0]
else:
if vertical:
style = 'vbar'
else:
style = 'bar'
if width is not None:
properties['xmaximum'] = width
@@ -734,8 +945,8 @@ class Bar(renpy.display.core.Displayable):
super(Bar, self).__init__(style=style, **properties)
self.adjustment = adjustment
self.focusable = adjustment.adjustable
self.focusable = True
# These are set when we are first rendered.
self.thumb_dim = 0
self.height = 0
@@ -746,14 +957,21 @@ class Bar(renpy.display.core.Displayable):
return [ self.style.fore_bar, self.style.aft_bar, self.style.thumb, self.style.thumb_shadow ]
def per_interact(self):
self.focusable = self.adjustment.adjustable
self.adjustment.register(self)
def render(self, width, height, st, at):
# Handle redrawing.
if self.value is not None:
redraw = self.value.periodic(st)
if redraw is not None:
renpy.display.render.redraw(self, redraw)
# Store the width and height for the event function to use.
self.width = width
self.height = height
range = self.adjustment.range
value = self.adjustment.value
page = self.adjustment.page
@@ -863,7 +1081,7 @@ class Bar(renpy.display.core.Displayable):
self.set_transform_event("hover")
def unfocus(self):
def unfocus(self, default=False):
super(Bar, self).unfocus()
self.set_transform_event("idle")
@@ -954,8 +1172,8 @@ class Conditional(renpy.display.layout.Container):
way, as that would break rollback.
"""
def __init__(self, condition, *args):
super(Conditional, self).__init__(*args)
def __init__(self, condition, *args, **properties):
super(Conditional, self).__init__(*args, **properties)
self.condition = condition
self.null = renpy.display.layout.Null()
@@ -983,21 +1201,45 @@ class Conditional(renpy.display.layout.Container):
class Timer(renpy.display.layout.Null):
def __init__(self, delay, function, repeat=False, args=(), kwargs={}):
super(Timer, self).__init__()
started = False
def __init__(self, delay, action=None, repeat=False, args=(), kwargs={}, replaces=None, **properties):
super(Timer, self).__init__(**properties)
if action is None:
raise Exception("A timer must have an action supplied.")
if delay <= 0:
raise Exception("A timer's delay must be > 0.")
# The delay.
self.delay = delay
self.function = function
# Should we repeat the event?
self.repeat = repeat
self.next_event = delay
# The time the next event should occur.
self.next_event = None
# The function and its arguments.
self.function = action
self.args = args
self.kwargs = kwargs
# Did we start the timer?
self.started = False
if replaces is not None:
self.started = replaces.started
self.next_event = replaces.next_event
def event(self, ev, x, y, st):
if not self.started:
self.started = True
self.next_event = st + self.delay
if self.next_event is None:
return
+711 -630
View File
File diff suppressed because it is too large Load Diff
+19 -14
View File
@@ -34,30 +34,24 @@ class ReportError(object):
# In the init method, Ren'Py is functioning reasonably normally.
def __init__(self):
self.font = renpy.display.text.get_font(renpy.store.style.default.font, 14, False, False, False)
self.flags = pygame.display.get_surface().get_flags()
self.size = pygame.display.get_surface().get_size()
# self.flags = pygame.display.get_surface().get_flags()
# self.size = pygame.display.get_surface().get_size()
self.size = (renpy.config.screen_width, renpy.config.screen_height)
# In the report method, Ren'Py may be in an ill-defined state.
def report(self, error_type):
import os.path
import pygame # W0404
pygame.display.init()
pygame.display.init()
pygame.display.set_caption("Ren'Py Error - left-click reloads, right-click quits")
msg = "Ren'Py has experienced " + error_type + ".\n"
msg += "Left-click or space reloads, right-click or escape exits."
screen = pygame.display.set_mode(self.size, self.flags, 32)
screen.fill((0, 0, 0, 255))
screen = pygame.display.set_mode(self.size, 0, 32)
y = 2
for l in msg.split('\n'):
surf = self.font.render(l, True, (255, 255, 255, 255), (0, 0, 0, 255))
screen.blit(surf, (2, y))
y += self.font.get_linesize()
pygame.display.flip() # E1120
pygame.time.set_timer(pygame.USEREVENT + 1, 50)
while True:
@@ -65,6 +59,17 @@ class ReportError(object):
if commandfile and os.path.exists(commandfile):
return True
screen.fill((0, 0, 0, 255))
y = 2
for l in msg.split('\n'):
surf = self.font.render(l, True, (255, 255, 255, 255), (0, 0, 0, 255))
screen.blit(surf, (2, y))
y += self.font.get_linesize()
pygame.display.flip() # E1120
ev = pygame.event.wait()
if ev.type == pygame.MOUSEBUTTONUP:
+22 -6
View File
@@ -104,7 +104,24 @@ def take_focuses():
for f in focus_list:
if f.x is None:
default_focus = f
def focus_coordinates():
"""
:doc: other
This attempts to find the coordinates of the currently-focused
displayable. If it can, it will return them as a (x, y, w, h)
tuple. If not, it will return a (None, None, None, None) tuple.
"""
current = get_focused()
for i in focus_list:
if i.widget == current and i.arg == argument:
return i.x, i.y, i.w, i.h
return None, None, None, None
# This is called before each interaction. It's purpose is to choose
# the widget that is focused, and to mark it as focused and all of
@@ -150,7 +167,7 @@ def before_interact(roots):
break
else:
current = None
# Otherwise, focus the default widget, or nothing.
if current is None:
@@ -162,13 +179,12 @@ def before_interact(roots):
else:
set_focused(None, None)
# Finally, mark the current widget as the focused widget, and
# all other widgets as unfocused.
for f, n in fwn:
if f is not current:
f.unfocus()
f.unfocus(default=True)
if current:
current.focus(default=True)
@@ -193,7 +209,7 @@ def change_focus(newfocus, default=False):
return rv
if current is not None:
current.unfocus()
current.unfocus(default=default)
current = widget
+929
View File
@@ -0,0 +1,929 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import renpy
from renpy.display.render import IDENTITY, DISSOLVE, IMAGEDISSOLVE, PIXELLATE
import pygame
import os
import os.path
import weakref
import array
import time
try:
import _renpy_tegl as gl; gl
import _renpy_pysdlgl as pysdlgl; pysdlgl
import renpy.display.gltexture
import renpy.display.glenviron
import renpy.display.glshader
import gltexture
import glenviron
gl.BGRA = 0x80E1
except ImportError:
gl = None
pysdlgl = None
# A list of cards that cause system/software crashes. There's no
# reason to put merely slow or incapable cards here, only ones for
# which GL operation is unsafe.
#
#
BLACKLIST = [
("S3 Graphics DeltaChrome", "1.4 20.00"),
]
# The logfile we use.
log_file = None
def open_log_file():
global log_file
if log_file is not None:
return log_file
# The OpenGL logfile.
try:
log_file = file(os.path.join(renpy.config.renpy_base, "opengl.txt"), "w")
except:
try:
log_file = file(os.path.join(renpy.config.savedir, "opengl.txt"), "w")
except:
log_file = None
class GLDraw(object):
def __init__(self):
# Did we do the first-time init?
self.did_init = False
# The GL environment to use.
self.environ = None
# The GL render-to-texture to use.
self.rtt = None
# The screen.
self.window = None
# The virtual size of the screen, as requested by the game.
self.virtual_size = None
# The physical size of the window we got.
self.physical_size = None
# Is the mouse currently visible?
self.mouse_old_visible = None
# The (x, y) and texture of the software mouse.
self.mouse_info = (0, 0, None)
# This is used to cache the surface->texture operation.
self.texture_cache = weakref.WeakKeyDictionary()
# The time of the last redraw.
self.last_redraw_time = 0
# Info.
self.info = { "renderer" : "gl" }
# Old value of fullscreen.
self.old_fullscreen = None
# We don't use a fullscreen surface.
self.fullscreen_surface = None
# The display info, from pygame.
self.display_info = None
# The amount we're upscaling by.
self.upscale_factor = 1.0
open_log_file()
def log(self, msg, *args):
"""
Logs a message to the logfile.
"""
if log_file is not None:
log_file.write(msg % args)
log_file.write("\n")
log_file.flush()
def set_mode(self, virtual_size, physical_size, fullscreen):
"""
This changes the video mode. It also initializes OpenGL, if it
can. It returns True if it was succesful, or False if OpenGL isn't
working for some reason.
"""
# If GL can't be loaded, give up.
if not gl:
return False
if not renpy.config.gl_enable:
self.log("GL Disabled.")
return False
if self.did_init:
self.deinit()
if fullscreen != self.old_fullscreen:
pygame.display.quit()
pygame.display.init()
self.display_info = pygame.display.Info()
renpy.display.interface.post_init()
self.old_fullscreen = fullscreen
self.log("")
self.log(renpy.version)
self.virtual_size = virtual_size
vwidth, vheight = virtual_size
pwidth, pheight = physical_size
# On a restart, restore the size.
if renpy.display.gl_size is not None and not fullscreen:
pwidth, pheight = renpy.display.gl_size
renpy.display.gl_size = None
# Ensure we're always at least 256x256, so we have a shot at rendering
# textures.
pwidth = max(pwidth, 256)
pheight = max(pheight, 256)
pwidth = min(self.display_info.current_w, pwidth)
pheight = min(self.display_info.current_h, pheight)
# Handle swap control.
vsync = os.environ.get("RENPY_GL_VSYNC", "1")
pygame.display.gl_set_attribute(pygame.GL_SWAP_CONTROL, int(vsync))
pygame.display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)
try:
if fullscreen:
self.log("fullscreen mode.")
self.window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN | pygame.OPENGL | pygame.DOUBLEBUF)
else:
self.log("windowed mode.")
self.window = pygame.display.set_mode((pwidth, pheight), pygame.RESIZABLE | pygame.OPENGL | pygame.DOUBLEBUF)
except pygame.error, e:
self.log("Could not get pygame screen: %r", e)
return False
pwidth, pheight = self.window.get_size()
self.physical_size = (pwidth, pheight)
self.log("Screen sizes: virtual=%r physical=%r" % (self.virtual_size, self.physical_size))
pwidth = max(1, pwidth)
pheight = max(1, pheight)
# Figure out the virtual box, which includes padding around
# the borders.
physical_ar = 1.0 * pwidth / pheight
virtual_ar = 1.0 * vwidth / vheight
if physical_ar >= virtual_ar:
x_padding = physical_ar * vheight - vwidth
y_padding = 0
px_padding = x_padding * pheight / vheight
py_padding = 0
else:
x_padding = 0
y_padding = ( 1.0 / physical_ar ) * vwidth - vheight
px_padding = 0
py_padding = y_padding * pwidth / vwidth
# The position of the physical screen, in virtual pixels
# (x, y, w, h). Since the physical screen will always contain
# the virtual screen, the corners are often off the virtual
# screen.
self.virtual_box = (
-x_padding / 2.0,
-y_padding / 2.0,
vwidth + x_padding,
vheight + y_padding)
# The location of the virtual screen on the physical screen, in
# physical pixels. (May not be 100% accurate, but it's good
# enough for screenshots.)
self.physical_box = (
int(px_padding / 2),
int(py_padding / 2),
pwidth - int(px_padding),
pheight - int(py_padding),
)
if not self.did_init:
if not self.init():
return False
self.did_init = True
# Set some default settings.
gl.Enable(gl.BLEND)
gl.BlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
gl.Enable(gl.CLIP_PLANE0)
gl.Enable(gl.CLIP_PLANE1)
gl.Enable(gl.CLIP_PLANE2)
gl.Enable(gl.CLIP_PLANE3)
self.environ.init()
self.rtt.init()
# Prepare a mouse call.
self.mouse_old_visible = None
return True
def deinit(self):
"""
De-initializes the system in preparation for a restart, or
quit. Flushes out all the textures while it's at it.
"""
# This should get rid of all of the cached textures.
renpy.display.render.free_memory()
self.texture_cache.clear()
gltexture.dealloc_textures()
if self.rtt:
self.rtt.deinit()
if self.environ:
self.environ.deinit()
def quit(self):
if not self.old_fullscreen:
renpy.display.gl_size = self.physical_size
self.log("Deallocating textures.")
gltexture.dealloc_textures()
self.log("Done deallocating textures.")
self.log("About to quit GL.")
pygame.display.quit()
self.log("Finished quit GL.")
def init(self):
"""
This does the first-time initialization of OpenGL, deciding
which subsystems to use.
"""
# Init glew.
pysdlgl.init_glew()
renderer = pysdlgl.get_string(gl.RENDERER)
version = pysdlgl.get_string(gl.VERSION)
# Log the GL version.
self.log("Vendor: %r", pysdlgl.get_string(gl.VENDOR))
self.log("Renderer: %r", renderer)
self.log("Version: %r", version)
self.log("Display Info: %s", self.display_info)
for r, v in BLACKLIST:
if renderer == r and version.startswith(v):
self.log("Blacklisted renderer/version.")
return False
extensions = set(pysdlgl.get_string(gl.EXTENSIONS).split(" "))
self.log("Extensions:")
for i in sorted(extensions):
self.log(" %s", i)
def use_subsystem(envvar, envval, *req_ext):
"""
Decides if we should used a particular subsystem, based on
environment variables and/or extensions. If the `envvar`
environment variable exists, this will return true iff
its value is `envval`. Otherwise, this will return true if
all of the required extensions are present, and false
otherwise.
"""
value = os.environ.get(envvar, "")
if value:
if value == envval:
return True
else:
return False
for i in req_ext:
if i not in extensions:
return False
return True
v = [ 0 ]
gl.GetIntegerv(gl.MAX_TEXTURE_UNITS_ARB, v)
self.log("Number of texture units: %d", v[0])
if v[0] < 4:
self.log("Not enough texture units.")
return False
gl.GetIntegerv(gl.MAX_CLIP_PLANES, v)
self.log("Number of clipping planes: %d", v[0])
# Pick a texture environment subsystem.
if use_subsystem(
"RENPY_GL_ENVIRON",
"shader",
"GL_ARB_vertex_shader",
"GL_ARB_fragment_shader"):
try:
self.log("Using shader environment.")
self.environ = glenviron.ShaderEnviron()
self.info["environ"] = "shader"
except Exception, e:
self.log("Initializing shader environment failed:")
self.log(str(e))
if self.environ is None:
if use_subsystem(
"RENPY_GL_ENVIRON",
"fixed",
"GL_ARB_texture_env_crossbar",
"GL_ARB_texture_env_combine"):
self.log("Using fixed-function environment (clause 1).")
self.environ = glenviron.FixedFunctionEnviron()
self.info["environ"] = "fixed"
elif use_subsystem(
"RENPY_GL_ENVIRON",
"fixed",
"GL_NV_texture_env_combine4"):
self.log("Using fixed-function environment (clause 2).")
self.environ = glenviron.FixedFunctionEnviron()
self.info["environ"] = "fixed"
else:
self.log("Can't find a workable environment.")
return False
# Pick a Render-to-texture subsystem.
if use_subsystem(
"RENPY_GL_RTT",
"fbo",
"GL_EXT_framebuffer_object",
"RENPY_nonexistent_extension"):
self.log("Using framebuffer_object RTT.")
self.rtt = glenviron.FramebufferRtt()
self.info["rtt"] = "fbo"
else:
self.log("Using copy RTT.")
self.rtt = glenviron.CopyRtt()
self.info["rtt"] = "copy"
# Do additional setup needed.
renpy.display.pgrender.set_bgra_masks()
return True
def should_redraw(self, needs_redraw, first_pass):
"""
Redraw whenever the screen needs it, but at least once every
.2 seconds. We rely on VSYNC to slow down our maximum
draw speed.
"""
rv = False
if needs_redraw:
rv = True
elif first_pass:
rv = True
elif time.time() > self.last_redraw_time + .20:
rv = True
else:
# Redraw if the mouse moves.
mx, my, tex = self.mouse_info
if tex and (mx, my) != pygame.mouse.get_pos():
rv = True
# Log the redraw time.
if rv:
self.last_redraw_time = time.time()
return True
else:
return False
def mutated_surface(self, surf):
if surf in self.texture_cache:
del self.texture_cache[surf]
def load_texture(self, surf, transient=False):
# Turn a surface into a texture grid.
rv = self.texture_cache.get(surf, None)
if rv is None:
rv = gltexture.texture_grid_from_surface(surf)
self.texture_cache[surf] = rv
return rv
# private
def undefine_clip(self):
"""
This makes the clipping undefined. It needs to be called when the
various matrices change, to ensure that the next call to set_clip
will re-set-up the clipping. Note that it does not remove the
clipping, but rather merely causes set_clip to change it.
"""
self.clip_cache = None
# private
def set_clip(self, clip):
if self.clip_cache == clip:
return
self.clip_cache = clip
minx, miny, maxx, maxy = clip
# OpenGL clipping works by only allowing coordinates where:
# a*x + b*y + c*z + d >= 0.
gl.ClipPlane(gl.CLIP_PLANE0, [1.0, 0.0, 0.0, -minx])
gl.ClipPlane(gl.CLIP_PLANE1, [0.0, 1.0, 0.0, -miny])
gl.ClipPlane(gl.CLIP_PLANE2, [-1.0, 0.0, 0.0, maxx])
gl.ClipPlane(gl.CLIP_PLANE3, [0.0, -1.0, 0.0, maxy])
def draw_screen(self, surftree, fullscreen_video):
"""
Draws the screen.
"""
forward = reverse = IDENTITY
surftree.is_opaque()
self.draw_render_textures(surftree, forward, reverse)
gl.Viewport(self.physical_box[0], self.physical_box[1], self.physical_box[2], self.physical_box[3])
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(0, self.virtual_size[0], self.virtual_size[1], 0, -1.0, 1.0)
gl.MatrixMode(gl.MODELVIEW)
gl.ClearColor(0.0, 0.0, 0.0, 0.0)
gl.Clear(gl.COLOR_BUFFER_BIT)
self.undefine_clip()
clip = (0, 0, self.virtual_size[0], self.virtual_size[1])
self.upscale_factor = 1.0 * self.physical_size[0] / self.virtual_size[0]
if renpy.audio.music.get_playing("movie") and renpy.display.video.fullscreen:
tex = renpy.display.video.get_movie_texture(self.virtual_size)
# self.load_texture(self.fullscreen_surface, transient=True)
self.draw_transformed(tex, clip, 0, 0, 1.0, forward, reverse)
else:
self.draw_transformed(surftree, clip, 0, 0, 1.0, forward, reverse)
self.draw_mouse()
# Release the CPU while we're waiting for things to actually
# draw to the screen.
renpy.display.core.cpu_idle.set()
pygame.display.flip()
renpy.display.core.cpu_idle.clear()
def draw_render_textures(self, what, forward, reverse):
"""
This is responsible for rendering things to textures,
as necessary.
"""
if not isinstance(what, renpy.display.render.Render):
return
render_what = False
if what.clipping:
if forward.xdy != 0 or forward.ydx != 0:
render_what = True
forward = reverse = IDENTITY
first = True
for child, cxo, cyo, focus, main in what.visible_children:
if what.forward:
child_forward = forward * what.forward
child_reverse = what.reverse * reverse
else:
child_forward = forward
child_reverse = reverse
self.draw_render_textures(child, child_forward, child_reverse)
if what.operation == DISSOLVE:
child.render_to_texture(what.operation_alpha)
if what.operation == IMAGEDISSOLVE:
child.render_to_texture(first or what.operation_alpha)
first = False
if what.operation == PIXELLATE:
p = what.operation_parameter
pc = child
while p > 1:
p /= 2
pc = self.get_half(pc)
if render_what:
what.render_to_texture(True)
def draw_transformed(self, what, clip, xo, yo, alpha, forward, reverse):
if isinstance(what, gltexture.TextureGrid):
self.set_clip(clip)
gltexture.blit(
what,
xo,
yo,
reverse,
alpha,
self.environ)
return
if not isinstance(what, renpy.display.render.Render):
raise Exception("Unknown drawing type. " + repr(what))
if isinstance(what, renpy.display.pgrender.Surface):
tex = self.load_texture(what)
self.draw_transformed(tex, clip, xo, yo, alpha, forward, reverse)
return
# Other draw modes.
if what.operation == DISSOLVE:
self.set_clip(clip)
gltexture.blend(
what.children[0][0].render_to_texture(what.operation_alpha),
what.children[1][0].render_to_texture(what.operation_alpha),
xo,
yo,
reverse,
alpha,
what.operation_complete,
self.environ)
return
elif what.operation == IMAGEDISSOLVE:
self.set_clip(clip)
gltexture.imageblend(
what.children[0][0].render_to_texture(True),
what.children[1][0].render_to_texture(what.operation_alpha),
what.children[2][0].render_to_texture(what.operation_alpha),
xo,
yo,
reverse,
alpha,
what.operation_complete,
what.operation_parameter,
self.environ)
return
if what.operation == PIXELLATE:
self.set_clip(clip)
p = what.operation_parameter
pc = what.children[0][0]
while p > 1:
p /= 2
pc = self.get_half(pc)
reverse *= renpy.display.render.Matrix2D(1.0 * what.width / pc.width, 0, 0, 1.0 * what.height / pc.height)
gltexture.blit(
pc,
xo,
yo,
reverse,
alpha,
self.environ,
nearest=True)
return
# Compute clipping.
if what.clipping:
# Non-aligned clipping uses RTT.
if forward.ydx != 0 or forward.xdy != 0:
tex = what.render_to_texture(True)
self.draw_transformed(tex, clip, xo, yo, alpha, forward, reverse)
return
minx, miny, maxx, maxy = clip
# Figure out the transformed width and height of this
# surface.
tw, th = reverse.transform(what.width, what.height)
minx = max(minx, min(xo, xo + tw))
maxx = min(maxx, max(xo, xo + tw))
miny = max(miny, min(yo, yo + th))
maxy = min(maxy, max(yo, yo + th))
clip = (minx, miny, maxx, maxy)
if what.forward and what.forward is not IDENTITY:
child_forward = forward * what.forward
child_reverse = what.reverse * reverse
else:
child_forward = forward
child_reverse = reverse
alpha = alpha * what.alpha
# If our alpha has hit 0, don't do anything.
if alpha <= 0.003: # (1 / 256)
return
for child, cxo, cyo, focus, main in what.visible_children:
cxo, cyo = reverse.transform(cxo, cyo)
self.draw_transformed(child, clip, xo + cxo, yo + cyo, alpha, child_forward, child_reverse)
def render_to_texture(self, what, alpha):
forward = reverse = IDENTITY
def draw_func():
if alpha:
gl.ClearColor(0.0, 0.0, 0.0, 0.0)
else:
gl.ClearColor(0.0, 0.0, 0.0, 1.0)
gl.Clear(gl.COLOR_BUFFER_BIT)
self.undefine_clip()
clip = (0, 0, what.width, what.height)
self.draw_transformed(what, clip, 0, 0, 1.0, forward, reverse)
what.is_opaque()
self.upscale_factor = 1.0
rv = gltexture.texture_grid_from_drawing(what.width, what.height, draw_func, self.rtt)
return rv
def is_pixel_opaque(self, what, x, y):
"""
Returns true if the pixel is not 100% transparent.
"""
if x < 0 or y < 0 or x >= what.width or y >= what.height:
return 0
what = what.subsurface((x, y, 1, 1))
forward = reverse = IDENTITY
gl.Viewport(0, 0, 1, 1)
gl.ClearColor(0.0, 0.0, 0.0, 0.0)
gl.Clear(gl.COLOR_BUFFER_BIT)
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(0, 1, 0, 1, -1, 1)
gl.MatrixMode(gl.MODELVIEW)
self.undefine_clip()
clip = (0, 0, 1, 1)
self.draw_transformed(what, clip, 0, 0, 1.0, forward, reverse)
a = array.array('b', (0,))
gl.ReadPixels(0, 0, 1, 1, gl.ALPHA, gl.BYTE, a)
what.kill()
return a[0]
def get_half(self, what):
"""
Gets a texture grid that's half the size of what..
"""
if what.half_cache:
return what.half_cache
reverse = renpy.display.render.Matrix2D(0.5, 0, 0, .5)
forward = renpy.display.render.Matrix2D(2.0, 0, 0, 2.0)
width = max(what.width / 2, 1)
height = max(what.height / 2, 1)
def draw_func():
gl.ClearColor(0.0, 0.0, 0.0, 1.0)
gl.Clear(gl.COLOR_BUFFER_BIT)
self.undefine_clip()
clip = (0, 0, width, height)
self.draw_transformed(what, clip, 0, 0, 1.0, forward, reverse)
if isinstance(what, renpy.display.render.Render):
what.is_opaque()
rv = gltexture.texture_grid_from_drawing(width, height, draw_func, self.rtt)
what.half_cache = rv
return rv
def update_mouse(self):
# The draw routine updates the mouse. There's no need to
# redraw it event-by-event.
return
def translate_mouse(self, x, y):
# Screen sizes.
pw, ph = self.physical_size
vw, vh = self.virtual_size
vx, vy, vw, vh = self.virtual_box
# Translate to fractional screen.
x = 1.0 * x / pw
y = 1.0 * y / ph
# Translate to virtual size.
x = vx + vw * x
y = vy + vh * y
x = int(x)
y = int(y)
x = max(0, x)
x = min(vw, x)
y = max(0, y)
y = min(vh, y)
return x, y
def mouse_event(self, ev):
x, y = getattr(ev, 'pos', pygame.mouse.get_pos())
return self.translate_mouse(x, y)
def get_mouse_pos(self):
x, y = pygame.mouse.get_pos()
return self.translate_mouse(x, y)
# Private.
def draw_mouse(self):
hardware, mx, my, tex = renpy.game.interface.get_mouse_info()
self.mouse_info = (mx, my, tex)
if self.mouse_old_visible != hardware:
pygame.mouse.set_visible(hardware)
self.mouse_old_visible = hardware
if not tex:
return
x, y = pygame.mouse.get_pos()
x -= mx
y -= my
pw, ph = self.physical_size
gl.Viewport(0, 0, pw, ph)
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(0, pw, ph, 0, -1.0, 1.0)
gl.MatrixMode(gl.MODELVIEW)
self.undefine_clip()
self.set_clip((0, 0, pw, ph))
gltexture.blit(
tex,
x,
y,
IDENTITY,
1.0,
self.environ)
def screenshot(self):
fb = renpy.display.pgrender.surface_unscaled(self.physical_size, False)
pysdlgl.store_framebuffer(fb, gl.BGRA)
rv = fb.subsurface(self.physical_box)
rv = renpy.display.pgrender.flip_unscaled(rv, False, True)
return rv
def free_memory(self):
self.texture_cache.clear()
gltexture.dealloc_textures()
def event_peek_sleep(self):
pass
+588
View File
@@ -0,0 +1,588 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file contains the code required to set up (and change) OpenGL texture
# environments to implement various effects.
try:
import _renpy_tegl as gl; gl
import _renpy_pysdlgl as pysdlgl; pysdlgl
except ImportError:
gl = None
pysdlgl = None
import glshader
# Constants, that are used to store the last kind of blend a class was
# used for. (So we can avoid changing the GL state unnecessarily.)
NONE = 0
BLIT = 1
BLEND = 2
IMAGEBLEND = 3
class Environ(object):
def blit(self):
"""
Set up a normal blit environment. The texture to be blitted should
be TEXTURE0.
"""
raise Exception("Not implemented.")
def blend(self, fraction):
"""
Set up an environment that blends from TEXTURE0 to TEXTURE1.
`fraction` is the fraction of the blend complete.
"""
raise Exception("Not implemented.")
def imageblend(self, fraction, ramp):
"""
Setup an environment that does an imageblend from TEXTURE1 to TEXTURE2.
The controlling image is TEXTURE0.
`fraction` is the fraction of the blend complete.
`ramp` is the length of the ramp.
"""
raise Exception("Not implemented.")
class FixedFunctionEnviron(Environ):
"""
This is an OpenGL environment that uses the fixed-function pipeline.
It requires ARB_texture_env_combine and ARB_texture_env_crossbar to
work.
"""
def init(self):
# The last blend environ used.
self.last = NONE
# The last ramp length asked for.
self.last_ramp = -1
# The last ramplen actually used.
self.last_ramplen = -1
# A table that maps ramp lengths to the setup of the fixed-function
# units.
self.ramp_setup = [
# Fields are:
# ramp length,
# unit 1 scale,
# unit 2 function,
# unit 2 scale,
(256, 1.0, gl.REPLACE, 1.0),
(128, 1.0, gl.REPLACE, 2.0),
(64, 1.0, gl.REPLACE, 4.0),
(32, 1.0, gl.ADD, 4.0),
(16, 2.0, gl.ADD, 4.0),
(8, 4.0, gl.ADD, 4.0),
]
def deinit(self):
"""
Called before changing the GL context.
"""
return
def disable(self, unit):
"""
Disables the given texture combiner.
"""
gl.ActiveTextureARB(unit)
gl.Disable(gl.TEXTURE_2D)
def combine_mode(self, unit,
color_function=gl.MODULATE,
color_arg0=gl.TEXTURE,
color_arg1=gl.PREVIOUS_ARB,
color_arg2=gl.CONSTANT_ARB,
color_source0=gl.SRC_COLOR,
color_source1=gl.SRC_COLOR,
color_source2=gl.SRC_COLOR,
color_scale=1.0,
alpha_function=gl.MODULATE,
alpha_arg0=gl.TEXTURE,
alpha_arg1=gl.PREVIOUS_ARB,
alpha_arg2=gl.CONSTANT_ARB,
alpha_source0=gl.SRC_ALPHA,
alpha_source1=gl.SRC_ALPHA,
alpha_source2=gl.SRC_ALPHA,
alpha_scale=1.0,
enable=True):
gl.ActiveTextureARB(unit)
if enable:
gl.Enable(gl.TEXTURE_2D)
else:
gl.Disable(gl.TEXTURE_2D)
gl.TexEnvi(gl.TEXTURE_ENV, gl.TEXTURE_ENV_MODE, gl.COMBINE_ARB)
gl.TexEnvi(gl.TEXTURE_ENV, gl.COMBINE_RGB_ARB, color_function)
gl.TexEnvi(gl.TEXTURE_ENV, gl.COMBINE_ALPHA_ARB, alpha_function)
gl.TexEnvi(gl.TEXTURE_ENV, gl.SOURCE0_RGB_ARB, color_arg0)
gl.TexEnvi(gl.TEXTURE_ENV, gl.OPERAND0_RGB_ARB, color_source0)
gl.TexEnvi(gl.TEXTURE_ENV, gl.SOURCE1_RGB_ARB, color_arg1)
gl.TexEnvi(gl.TEXTURE_ENV, gl.OPERAND1_RGB_ARB, color_source1)
gl.TexEnvi(gl.TEXTURE_ENV, gl.SOURCE2_RGB_ARB, color_arg2)
gl.TexEnvi(gl.TEXTURE_ENV, gl.OPERAND2_RGB_ARB, color_source2)
gl.TexEnvi(gl.TEXTURE_ENV, gl.SOURCE0_ALPHA_ARB, alpha_arg0)
gl.TexEnvi(gl.TEXTURE_ENV, gl.OPERAND0_ALPHA_ARB, alpha_source0)
gl.TexEnvi(gl.TEXTURE_ENV, gl.SOURCE1_ALPHA_ARB, alpha_arg1)
gl.TexEnvi(gl.TEXTURE_ENV, gl.OPERAND1_ALPHA_ARB, alpha_source1)
gl.TexEnvi(gl.TEXTURE_ENV, gl.SOURCE2_ALPHA_ARB, alpha_arg2)
gl.TexEnvi(gl.TEXTURE_ENV, gl.OPERAND2_ALPHA_ARB, alpha_source2)
gl.TexEnvf(gl.TEXTURE_ENV, gl.RGB_SCALE_ARB, color_scale)
gl.TexEnvf(gl.TEXTURE_ENV, gl.ALPHA_SCALE, alpha_scale)
def blit(self):
if self.last != BLIT:
# Set unit 0 to modulate.
self.combine_mode(gl.TEXTURE0_ARB,
color_function=gl.MODULATE,
alpha_function=gl.MODULATE)
# Disable units 1, 2 and 3.
self.disable(gl.TEXTURE1_ARB)
self.disable(gl.TEXTURE2_ARB)
self.disable(gl.TEXTURE3_ARB)
self.last = BLIT
def blend(self, fraction):
if self.last != BLEND:
# Get texture 0.
self.combine_mode(gl.TEXTURE0_ARB,
color_function=gl.REPLACE,
alpha_function=gl.REPLACE)
# Use interpolate to combine texture 0 with texture 1, as
# controlled by the constant of texture unit 1.
self.combine_mode(gl.TEXTURE1_ARB,
color_function=gl.INTERPOLATE_ARB,
color_arg0=gl.TEXTURE1_ARB,
color_arg1=gl.TEXTURE0_ARB,
alpha_function=gl.INTERPOLATE_ARB,
alpha_arg0=gl.TEXTURE1_ARB,
alpha_arg1=gl.TEXTURE0_ARB)
# Combine the interpolated result with the primary color, to
# allow for tinting and alpha adjustments.
self.combine_mode(gl.TEXTURE2_ARB,
color_function=gl.MODULATE,
color_arg0=gl.PREVIOUS_ARB,
color_arg1=gl.PRIMARY_COLOR_ARB,
alpha_function=gl.MODULATE,
alpha_arg0=gl.PREVIOUS_ARB,
alpha_arg1=gl.PRIMARY_COLOR_ARB,
enable=False)
# Disable texture unit 3.
self.disable(gl.TEXTURE3_ARB)
self.last = BLEND
gl.ActiveTextureARB(gl.TEXTURE1_ARB)
gl.TexEnvfv(gl.TEXTURE_ENV, gl.TEXTURE_ENV_COLOR, (fraction, fraction, fraction, fraction))
def imageblend(self, fraction, ramp):
if self.last != IMAGEBLEND or self.last_ramp != ramp:
# Figure out the details of the ramp.
for i in self.ramp_setup:
ramplen, t0scale, t1function, t1scale = i
# We round the ramplen down, unless we're below the
# smallest size, in which case we increase it.
if ramplen <= ramp:
break
# Unit 0 loads in the control image, and adds/subtracts an
# offset to/from it. (We'll set it up to subtract here,
# and change this later on as necessary.)
#
# It multiplies this result by up to 4.
self.combine_mode(gl.TEXTURE0_ARB,
color_function=gl.SUBTRACT_ARB,
alpha_function=gl.SUBTRACT_ARB,
color_arg1=gl.CONSTANT_ARB,
alpha_arg1=gl.CONSTANT_ARB,
color_scale=t0scale,
alpha_scale=t0scale)
# Unit 1 will multiply the result of stage 1 by up to 8.
#
# It also takes the first source texture, but we don't
# access it directly yet.
self.combine_mode(gl.TEXTURE1_ARB,
color_function=t1function,
alpha_function=t1function,
color_arg0=gl.PREVIOUS_ARB,
color_arg1=gl.PREVIOUS_ARB,
alpha_arg0=gl.PREVIOUS_ARB,
alpha_arg1=gl.PREVIOUS_ARB,
color_scale=t1scale,
alpha_scale=t1scale)
# Unit 2 uses the result of unit 1 to interpolate between the
# unit 1 and unit 2 textures.
self.combine_mode(gl.TEXTURE2_ARB,
color_function=gl.INTERPOLATE_ARB,
alpha_function=gl.INTERPOLATE_ARB,
color_arg0=gl.TEXTURE2_ARB,
color_arg1=gl.TEXTURE1_ARB,
color_arg2=gl.PREVIOUS_ARB,
alpha_arg0=gl.TEXTURE2_ARB,
alpha_arg1=gl.TEXTURE1_ARB,
alpha_arg2=gl.PREVIOUS_ARB)
# Finally, Unit 3 modulates the result of unit 2 with the color.
self.combine_mode(gl.TEXTURE3_ARB,
color_function=gl.MODULATE,
color_arg0=gl.PREVIOUS_ARB,
color_arg1=gl.PRIMARY_COLOR_ARB,
alpha_function=gl.MODULATE,
alpha_arg0=gl.PREVIOUS_ARB,
alpha_arg1=gl.PRIMARY_COLOR_ARB,
enable=False)
self.last = IMAGEBLEND
self.last_ramp = ramp
self.last_ramplen = ramplen
# Compute the offset to apply to the alpha.
start = -1.0
end = self.last_ramplen / 256.0
offset = start + ( end - start) * fraction
# Decide if we're adding or subtracting.
if offset < 0:
function = gl.SUBTRACT_ARB
offset = -offset
else:
function = gl.ADD
# Setup unit 0 as appropriate.
gl.ActiveTextureARB(gl.TEXTURE0_ARB)
gl.TexEnvi(gl.TEXTURE_ENV, gl.COMBINE_RGB_ARB, function)
gl.TexEnvi(gl.TEXTURE_ENV, gl.COMBINE_ALPHA_ARB, function)
gl.TexEnvfv(gl.TEXTURE_ENV, gl.TEXTURE_ENV_COLOR, (offset, offset, offset, offset))
class ShaderEnviron(object):
"""
This is an environment that uses shaders.
"""
def init(self):
self.blit_program = glshader.blit_program()
self.blit_tex0_uniform = gl.GetUniformLocationARB(
self.blit_program,
"tex0")
self.blend_program = glshader.blend_program()
self.blend_done_uniform = gl.GetUniformLocationARB(
self.blend_program,
"done")
self.blend_tex0_uniform = gl.GetUniformLocationARB(
self.blend_program,
"tex0")
self.blend_tex1_uniform = gl.GetUniformLocationARB(
self.blend_program,
"tex1")
self.imageblend_program = glshader.imageblend_program()
self.imageblend_tex0_uniform = gl.GetUniformLocationARB(
self.imageblend_program,
"tex0")
self.imageblend_tex1_uniform = gl.GetUniformLocationARB(
self.imageblend_program,
"tex1")
self.imageblend_tex2_uniform = gl.GetUniformLocationARB(
self.imageblend_program,
"tex2")
self.imageblend_offset_uniform = gl.GetUniformLocationARB(
self.imageblend_program,
"offset")
self.imageblend_multiplier_uniform = gl.GetUniformLocationARB(
self.imageblend_program,
"multiplier")
self.last = NONE
def deinit(self):
"""
Called before changing the GL context.
"""
gl.DeleteObjectARB(self.blit_program)
gl.DeleteObjectARB(self.blend_program)
gl.DeleteObjectARB(self.imageblend_program)
return
def blit(self):
if self.last != BLIT:
gl.UseProgramObjectARB(self.blit_program)
gl.Uniform1iARB(self.blit_tex0_uniform, 0)
self.last = BLIT
def blend(self, fraction):
if self.last != BLEND:
gl.UseProgramObjectARB(self.blend_program)
gl.Uniform1iARB(self.blend_tex0_uniform, 0)
gl.Uniform1iARB(self.blend_tex1_uniform, 1)
self.last = BLEND
gl.Uniform1fARB(self.blend_done_uniform, fraction)
def imageblend(self, fraction, ramp):
if self.last != IMAGEBLEND:
gl.UseProgramObjectARB(self.imageblend_program)
gl.Uniform1iARB(self.imageblend_tex0_uniform, 0)
gl.Uniform1iARB(self.imageblend_tex1_uniform, 1)
gl.Uniform1iARB(self.imageblend_tex2_uniform, 2)
self.last = IMAGEBLEND
# Prevent a DBZ if the user gives us a 0 ramp.
if ramp < 1:
ramp = 1
# Compute the offset to apply to the alpha.
start = -1.0
end = ramp / 256.0
offset = start + ( end - start) * fraction
# Setup the multiplier and the offset.
gl.Uniform1fARB(self.imageblend_multiplier_uniform, 256.0 / ramp)
gl.Uniform1fARB(self.imageblend_offset_uniform, offset)
class Rtt(object):
"""
Subclasses of this class handle rendering to a texture.
"""
def begin(self):
"""
This function should be called when a Render-to-texture
session begins. It's responsible for setting the GPU to
RTT mode.
"""
raise Exception("Not implemented.")
def render(self, texture, x, y, w, h, draw_func):
"""
This function is called to trigger a rendering to a texture.
`x`, `y`, `w`, and `h` specify the location and dimensions of
the sub-image to render to the texture. `draw_func` is called
to render the texture.
"""
raise Exception("Not implemented.")
def end(self):
"""
This is called when a Render-to-texture session ends.
"""
raise Exception("Not implemented.")
class CopyRtt(object):
"""
This class uses texture copying to implement Render-to-texture.
"""
def init(self):
pass
def deinit(self):
"""
Called before changing the GL context.
"""
return
def begin(self):
"""
This function should be called when a Render-to-texture
session begins. It's responsible for setting the GPU to
RTT mode.
"""
def render(self, texture, x, y, w, h, draw_func):
"""
This function is called to trigger a rendering to a texture.
`x`, `y`, `w`, and `h` specify the location and dimensions of
the sub-image to render to the texture. `draw_func` is called
to render the texture.
"""
gl.Viewport(0, 0, w, h)
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(x, x + w, y, y + h, -1, 1)
gl.MatrixMode(gl.MODELVIEW)
draw_func()
gl.BindTexture(gl.TEXTURE_2D, texture)
gl.CopyTexSubImage2D(
gl.TEXTURE_2D,
0,
0,
0,
0,
0,
w,
h)
def end(self):
"""
This is called when a Render-to-texture session ends.
"""
class FramebufferRtt(object):
"""
This class uses the framebuffer object to do RTT.
"""
def init(self):
# This maps a texture to the framebuffer object that
# can write to that texture.
self.texture_to_fbo = { }
def deinit(self):
"""
Called before changing the GL context.
"""
for i in self.texture_to_fbo.itervalues():
gl.DeleteFramebuffersEXT(1, [ i ])
self.texture_to_fbo.clear()
def get_fbo(self, texture):
if texture in self.texture_to_fbo:
return self.texture_to_fbo[texture]
fbos = [ 0 ]
gl.GenFramebuffersEXT(1, fbos)
fbo = fbos[0]
gl.BindFramebufferEXT(gl.FRAMEBUFFER_EXT, fbo)
gl.FramebufferTexture2DEXT(
gl.FRAMEBUFFER_EXT,
gl.COLOR_ATTACHMENT0_EXT,
gl.TEXTURE_2D,
texture,
0)
self.texture_to_fbo[texture] = fbo
return fbo
def begin(self):
"""
This function should be called when a Render-to-texture
session begins. It's responsible for setting the GPU to
RTT mode.
"""
def render(self, texture, x, y, w, h, draw_func):
"""
This function is called to trigger a rendering to a texture.
`x`, `y`, `w`, and `h` specify the location and dimensions of
the sub-image to render to the texture. `draw_func` is called
to render the texture.
"""
fbo = self.get_fbo(texture)
gl.BindFramebufferEXT(gl.FRAMEBUFFER_EXT, fbo)
gl.Viewport(0, 0, w, h)
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(x, x + w, y, y + h, -1, 1)
gl.MatrixMode(gl.MODELVIEW)
draw_func()
def end(self):
"""
This is called when a Render-to-texture session ends.
"""
gl.BindFramebufferEXT(gl.FRAMEBUFFER_EXT, 0)
+168
View File
@@ -0,0 +1,168 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file contains GLSL shader code, and code to load shaders.
import array
try:
import _renpy_tegl as gl; gl
import _renpy_pysdlgl as pysdlgl; pysdlgl
except ImportError:
gl = None
pysdlgl = None
VERTEX_SHADER = """
void main() {
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_TexCoord[1] = gl_MultiTexCoord1;
gl_TexCoord[2] = gl_MultiTexCoord2;
gl_ClipVertex = gl_ModelViewMatrix * gl_Vertex;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
gl_FrontColor = gl_Color;
gl_BackColor = gl_Color;
}
"""
BLIT_SHADER = """
uniform sampler2D tex0;
void main()
{
vec4 color0 = texture2D(tex0, gl_TexCoord[0].st);
gl_FragColor = color0 * gl_Color;
}
"""
BLEND_SHADER = """
uniform sampler2D tex0;
uniform sampler2D tex1;
uniform float done;
void main()
{
vec4 color0 = texture2D(tex0, gl_TexCoord[0].st);
vec4 color1 = texture2D(tex1, gl_TexCoord[1].st);
gl_FragColor = mix(color0, color1, done) * gl_Color;
}
"""
IMAGEBLEND_SHADER = """
uniform sampler2D tex0;
uniform sampler2D tex1;
uniform sampler2D tex2;
uniform float offset;
uniform float multiplier;
void main()
{
vec4 color0 = texture2D(tex0, gl_TexCoord[0].st);
vec4 color1 = texture2D(tex1, gl_TexCoord[1].st);
vec4 color2 = texture2D(tex2, gl_TexCoord[2].st);
float a = clamp((color0.a + offset) * multiplier, 0.0, 1.0);
gl_FragColor = mix(color1, color2, a) * gl_Color;
}
"""
def check_status(handle, type):
"""
Checks the status of a shader or program. If it fails, then an
exception is raised.
"""
status = [ 0 ]
gl.GetObjectParameterivARB(handle, type, status)
if status[0] == 0:
log_length_list = [ 0 ]
gl.GetObjectParameterivARB(handle, gl.OBJECT_INFO_LOG_LENGTH_ARB, log_length_list)
log_length = log_length_list[0]
log = array.array('c', ' ' * log_length)
gl.GetInfoLogARB(handle, log_length, [ 0 ], log)
raise Exception("Shader error: %s" % log.tostring())
def compile_shader(kind, source):
"""
Allocates and compiles a shader.
"""
handle = gl.CreateShaderObjectARB(kind)
gl.ShaderSourceARB(handle, 1, [ source ], [ len(source) ])
gl.CompileShaderARB(handle)
check_status(handle, gl.OBJECT_COMPILE_STATUS_ARB)
return handle
def compile_program(vertex, fragment):
"""
Compiles a pair of shaders into a program.
"""
vertex_shader = compile_shader(gl.VERTEX_SHADER_ARB, vertex)
fragment_shader = compile_shader(gl.FRAGMENT_SHADER_ARB, fragment)
program = gl.CreateProgramObjectARB()
gl.AttachObjectARB(program, vertex_shader)
gl.AttachObjectARB(program, fragment_shader)
gl.LinkProgramARB(program)
check_status(program, gl.OBJECT_LINK_STATUS_ARB)
gl.UseProgramObjectARB(program)
gl.DeleteObjectARB(vertex_shader)
gl.DeleteObjectARB(fragment_shader)
return program
# These return the standard programs, compiled and ready to use.
def blit_program():
return compile_program(VERTEX_SHADER, BLIT_SHADER)
def blend_program():
return compile_program(VERTEX_SHADER, BLEND_SHADER)
def imageblend_program():
return compile_program(VERTEX_SHADER, IMAGEBLEND_SHADER)
+962
View File
@@ -0,0 +1,962 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import collections
import pygame; pygame # other modules might depend on pygame.
try:
import _renpy_tegl as gl; gl
import _renpy_pysdlgl as pysdlgl; pysdlgl
except ImportError:
gl = None
pysdlgl = None
import renpy
# The maximum size of a texture.
MAX_SIZE = 512
# Possible sizes for a texture.
SIZES = [ 512, 256, 128, 64 ]
def check_error():
"""
This checks for an opengl error, and throws an exception if it occurs.
"""
err = gl.GetError()
if err:
raise Exception("GL Error: 0x%x" % err)
# A list of texture number allocated.
texture_numbers = [ ]
class Texture(object):
"""
This object stores information about an OpenGL texture.
"""
def __init__(self, width, height):
# The width and height of this texture.
self.width = width
self.height = height
# The number of the OpenGL texture this texture object
# represents.
self.generation = 0
self.number = None
# True if the texture has been created inside the GPU.
self.created = False
# These are used to map an index into texture coordinates.
self.xmul = 0
self.xadd = 0
self.ymul = 0
self.yadd = 0
# These contained the premultiplied (but not GPU-loaded)
# surface. They allow us to defer loading until the surface is
# needed.
self.premult = None
self.premult_size = None
self.premult_left = None
self.premult_right = None
self.premult_top = None
self.premult_bottom = None
# True if we're in NEAREST mode. False if we're in LINEAR mode.
self.nearest = False
# The free list we should be put on, or None if we're already on
# a free list.
self.free_list = None
def __del__(self):
# Release the surface.
self.premult = None
self.premult_size = None
self.premult_left = None
self.premult_right = None
self.premult_top = None
self.premult_bottom = None
# The test needs to be here so we don't try to append during
# interpreter shutdown.
if self.free_list is not None:
try:
self.free_list.append(self)
self.free_list = None
except TypeError:
pass # Let's not error on shutdown.
def load_surface(self, surf, x, y, w, h,
border_left, border_top, border_right, border_bottom):
"""
Loads a pygame surface into this texture rectangle.
"""
# This just queues the surface up for loading. The actual loading
# occurs when the texture is first needed. This ensures that the
# texture loading only occurs in the GL thread.
self.premult = pysdlgl.premultiply(
surf, x, y, w, h,
border_left, border_top, border_right, border_bottom)
self.premult_size = (w, h)
def make_nearest(self):
"""
Causes this texture to be rendered in nearest-neighbor mode.
"""
if self.nearest:
return
gl.BindTexture(gl.TEXTURE_2D, self.number)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
self.nearest = True
def make_linear(self):
"""
Causes this texture to be rendered in linear interpolation mode.
"""
if not self.nearest:
return
gl.BindTexture(gl.TEXTURE_2D, self.number)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
self.nearest = False
def make_ready(self):
"""
Makes the texture ready for use.
"""
self.allocate()
if self.premult:
w, h = self.premult_size
gl.BindTexture(gl.TEXTURE_2D, self.number)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
self.nearest = False
# If we haven't initalized the texture yet, and we're
# smaller than it, load in the empty texture.
if w < self.width or h < self.height:
if not self.created:
pysdlgl.load_premultiplied(
None,
self.width,
self.height,
0,
gl.BGRA)
self.created = True
# Otherwise, either load or replace the texture.
pysdlgl.load_premultiplied(
self.premult,
w,
h,
self.created,
gl.BGRA)
# Needs to be here twice, since we may not go through the w < SIDE
# h < SIDE thing all the time.
self.created = True
# Finally, load in the default math.
self.xadd = self.yadd = 0
self.xmul = 1.0 / self.width
self.ymul = 1.0 / self.height
# We don't need to be loaded anymore.
self.premult = None
self.premult_size = None
def render_to(self, x, y, draw_func, rtt):
self.allocate()
if not self.created:
gl.BindTexture(gl.TEXTURE_2D, self.number)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
self.nearest = False
pysdlgl.load_premultiplied(
None,
self.width,
self.height,
0,
gl.BGRA)
self.created = True
rtt.render(self.number, x, y, self.width, self.height, draw_func)
self.xadd = 0
self.yadd = 0
self.xmul = 1.0 / self.width
self.ymul = 1.0 / self.height
def allocate(self):
"""
This allocates a texture number, if necessary.
"""
if self.number is not None:
return
texnums = [ 0 ]
gl.GenTextures(1, texnums)
self.number = texnums[0]
self.created = False
texture_numbers.append(texnums[0])
# This is a map from texture sizes to a list of free textures of that
# size.
free_textures = collections.defaultdict(list)
# The total size (in bytes) of all the textures that have been allocated.
total_texture_size = 0
# This allocates a texture, either from the free list, or by asking
# gl.
def alloc_texture(width, height):
"""
Allocate a texture, either from the freelist or by asking GL. The
returned texture has a reference count of 1.
"""
global total_texture_size
l = free_textures[width, height]
if l:
rv = l.pop()
else:
rv = Texture(width, height)
total_texture_size += width * height * 4
rv.free_list = l
return rv
def dealloc_textures():
global texture_numbers
for t in texture_numbers:
gl.DeleteTextures(1, [ t ])
texture_numbers = [ ]
free_textures.clear()
def compute_subrow(row, offset, width):
"""
Given a row (or column), this computes a subrow starting at the given
offset and having the given width.
It returns two list. The first is a list of (offset, width,
output-tile) tuples. The second is a list of integers, giving the
input tile corresponding to each output tile.
"""
# An iterator over row.
rowi = iter(row)
# The output row and the output tile list.
outrow = [ ]
tiles = [ ]
# The output tile index.
outtile = 0
try:
ioff, iwidth, itile = rowi.next()
# Consume the offset.
while True:
if offset < iwidth:
ioff += offset
iwidth -= offset
break
offset -= iwidth
ioff, iwidth, itile = rowi.next()
# Consume the width.
while True:
if width < iwidth:
outrow.append((ioff, width, outtile))
tiles.append(itile)
outtile += 1
break
outrow.append((ioff, iwidth, outtile))
tiles.append(itile)
outtile += 1
width -= iwidth
ioff, iwidth, itile = rowi.next()
except StopIteration:
pass
return outrow, tiles
class TextureGrid(object):
"""
This represents one or more textures that cover a rectangular
area.
"""
def __init__(self, width, height):
# The width and height of this TextureGrid
self.width = width
self.height = height
# For each row of tiles, a tuple giving:
# - The y offset within the texture.
# - The height of the row.
# - The rowindex in tiles.
self.rows = [ ]
# For each column of tiles, a tuple giving.
# - The x offset within the texture.
# - The width of the column.
# - The colindex in tiles.
self.columns = [ ]
# The actual grid of texture titles, a list of lists of
# textures. This is looked up by looking up rowindex and
# colindex.
self.tiles = [ ]
# If it exists, a TextureGrid that is half the size of this
# one.
self.half_cache = None
def get_size(self):
return self.width, self.height
def subsurface(self, (x, y, w, h)):
"""
This produces a texture grid containing a rectangle "cut out"
of this texture grid.
"""
rv = TextureGrid(w, h)
rv.rows, rowtiles = compute_subrow(self.rows, y, h)
rv.columns, coltiles = compute_subrow(self.columns, x, w)
for i in rowtiles:
row = [ ]
for j in coltiles:
row.append(self.tiles[i][j])
rv.tiles.append(row)
return rv
def make_ready(self, nearest=False):
"""
Makes ready all the tile-textures in this texture grid.
"""
for row in self.tiles:
for t in row:
t.make_ready()
if nearest:
t.make_nearest()
else:
t.make_linear()
# This is a cache from (width, size) to the results of compute_tiling.
tiling_cache = { }
def compute_tiling(width, max_size=MAX_SIZE):
"""
This computes a tiling for an image with the given width (or
height). It takes a width as an argument, and returns two lists.
The first is a list of (offset, width, index) tuples, as are used
in TextureGrid to determine how to blit an image to the screen.
The second is a list of (offset, copy-width, total-width) tuples
that are used to create the tiles.
While we're thinking about this as if it's working horizontally
(x, width, etc), it
"""
# Check the cache.
key = (width, max_size)
if key in tiling_cache:
return tiling_cache[key]
# width is the remaining width, not including any borders
# required.
# The x-offset, relative to the left side of the surface.
x = 0
# The list of row tuples.
row = [ ]
# The list of tile tuples.
tiles = [ ]
# The index into the row.
row_index = 0
while width:
# The size of the left border of this tile.
left_border = 1
# The size of the right border of this tile.
right_border = 1
# Figure out the texture size to use.
for size in SIZES:
if size > max_size:
continue
# Ensure each texture is at least 2/3rds full. (Except the
# smallest.)
if size * .66 <= width + left_border:
break
# The number of pixels to display to the user from this tile.
row_size = min(width, size - left_border - right_border)
#Add to the results.
row.append((left_border, row_size, row_index))
tiles.append((x - left_border, row_size + left_border + right_border, size))
# Update the counters.
row_index += 1
x += row_size
width -= row_size
tiling_cache[key] = (row, tiles)
return row, tiles
def first_last(l):
"""
Iterates over list l. Yields (first, last, item) triples, where first
and last are true if the item is the first or last element in l,
respectively.
"""
n = len(l)
for i in range(n):
first = (i == 0)
last = (i == n - 1)
yield first, last, l[i]
def texture_grid_from_surface(surf):
"""
This takes a Surface and turns it into a TextureGrid.
"""
width, height = surf.get_size()
rv = TextureGrid(width, height)
rv.columns, texcolumns = compute_tiling(width)
rv.rows, texrows = compute_tiling(height)
for border_top, border_bottom, (y, height, texheight) in first_last(texrows):
row = [ ]
for border_left, border_right, (x, width, texwidth) in first_last(texcolumns):
tex = alloc_texture(texwidth, texheight)
tex.load_surface(surf, x, y, width, height,
border_left, border_top, border_right, border_bottom)
row.append(tex)
rv.tiles.append(row)
return rv
def texture_grid_from_drawing(width, height, draw_func, rtt):
"""
This creates a texture grid of `width` by `height` by using
draw_func to draw to the screen.
"""
rtt.begin()
rv = TextureGrid(width, height)
pwidth, pheight = renpy.display.draw.physical_size
rv.columns, texcolumns = compute_tiling(width, pwidth)
rv.rows, texrows = compute_tiling(height, pheight)
for y, height, texheight in texrows:
row = [ ]
for x, width, texwidth in texcolumns:
tex = alloc_texture(texwidth, texheight)
tex.render_to(x, y, draw_func, rtt)
row.append(tex)
rv.tiles.append(row)
rtt.end()
return rv
def align_axes(*args):
"""
This takes n axes, each a list consisting of (offset, size, index)
tuples. It returns a list of n lists. For each of the n lists, the
ith element will be the same size. The indexes will appear in the
same order they did in the original list.
This is used to combine the grids of two or more texgrids into a
single grid.
"""
# The lists we're building.
rv = [ [] for i in args ]
# The index of the current element, for each member of args.
cur = [ 0 for i in args ]
# The parts of the current element.
offset = [ i[0][0] for i in args ]
size = [ i[0][1] for i in args ]
index = [ i[0][2] for i in args ]
# Cache it here to save function calls.
nargs = len(args)
loop = True
while loop:
# Figure out the minimum size.
minsize = min(size)
for i in xrange(nargs):
# Create an entry of minsize.
rv[i].append((offset[i], minsize, index[i]))
# Adjust the offset and size.
offset[i] += minsize
size[i] -= minsize
# If the size fell to 0, then load the next element from
# the arguments into offset, size, index. If we can't
# we're done.
if size[i] == 0:
cur[i] += 1
if cur[i] >= len(args[i]):
loop = False
else:
offset[i], size[i], index[i] = args[i][cur[i]]
return rv
def blit(tg, sx, sy, transform, alpha, environ, nearest=False):
"""
This draws texgrid `tg` to the screen. `sx` and `sy` are offsets from
the upper-left corner of the screen.
`transform` is the transform to apply to the texgrid, when going from
texgrid coordinates to screen coordinates.
`alpha` is the alpha multiplier applied, from 0.0 to 1.0.
"""
tg.make_ready(nearest)
environ.blit()
gl.Color4f(alpha, alpha, alpha, alpha)
y = 0
for texy, texh, rowindex in tg.rows:
x = 0
for texx, texw, colindex in tg.columns:
tex = tg.tiles[rowindex][colindex]
draw_rectangle(
sx, sy,
x, y,
texw, texh,
transform,
tex, texx, texy,
None, 0, 0,
None, 0, 0,
)
x += texw
y += texh
def blend(tg0, tg1, sx, sy, transform, alpha, fraction, environ):
"""
Blends two textures to the screen.
`tg0` and `tg1` are the texture.
`sx` and `sy` are the offsets from the upper-left corner of the screen.
`transform` is the transform to apply to the texgrid, when going from
texgrid coordinates to screen coordinates.
`alpha` is the alpha multiplier applied, from 0.0 to 1.0.
`fraction` is the fraction of the second texture to show.
"""
tg0.make_ready()
tg1.make_ready()
environ.blend(fraction)
gl.Color4f(alpha, alpha, alpha, alpha)
y = 0
rows0, rows1 = align_axes(tg0.rows, tg1.rows)
cols0, cols1 = align_axes(tg0.columns, tg1.columns)
# t0 = texture 0, t1 = texture 1.
# x, y - index into the texture.
# w, h - width and height to draw.
# ri, ci - row index, column index in tiles.
for (t0y, t0h, t0ri), (t1y, t1h, t1ri) in zip(rows0, rows1):
x = 0
for (t0x, t0w, t0ci), (t1x, t1w, t1ci) in zip(cols0, cols1):
t0 = tg0.tiles[t0ri][t0ci]
t1 = tg1.tiles[t1ri][t1ci]
draw_rectangle(
sx, sy,
x, y,
t0w, t0h,
transform,
t0, t0x, t0y,
t1, t1x, t1y,
None, 0, 0,
)
x += t0w
y += t0h
def imageblend(tg0, tg1, tg2, sx, sy, transform, alpha, fraction, ramp, environ):
"""
This uses texture 0 to control the blending of tetures 1 and 2 to
the screen.
`tg0`, `tg1`, and `tg2` are the textures.
`sx` and `sy` are the offsets from the upper-left corner of the screen.
`transform` is the transform to apply to the texgrid, when going from
texgrid coordinates to screen coordinates.
`alpha` is the alpha multiplier applied, from 0.0 to 1.0.
`fraction` is the fraction of the second texture to show.
`ramp` is the length of the blending ramp to use.
"""
tg0.make_ready()
tg1.make_ready()
tg2.make_ready()
environ.imageblend(fraction, ramp)
gl.Color4f(alpha, alpha, alpha, alpha)
y = 0
rows0, rows1, rows2 = align_axes(tg0.rows, tg1.rows, tg2.rows)
cols0, cols1, cols2 = align_axes(tg0.columns, tg1.columns, tg2.columns)
# t0 = texture 0, t1 = texture 1.
# x, y - index into the texture.
# w, h - width and height to draw.
# ri, ci - row index, column index in tiles.
for (t0y, t0h, t0ri), (t1y, t1h, t1ri), (t2y, t2h, t2ri) in zip(rows0, rows1, rows2):
x = 0
for (t0x, t0w, t0ci), (t1x, t1w, t1ci), (t2x, t2w, t2ci) in zip(cols0, cols1, cols2):
t0 = tg0.tiles[t0ri][t0ci]
t1 = tg1.tiles[t1ri][t1ci]
t2 = tg2.tiles[t2ri][t2ci]
draw_rectangle(
sx, sy,
x, y,
t0w, t0h,
transform,
t0, t0x, t0y,
t1, t1x, t1y,
t2, t2x, t2y,
)
x += t0w
y += t0h
def draw_rectangle(
sx,
sy,
x,
y,
w,
h,
transform,
tex0, tex0x, tex0y,
tex1, tex1x, tex1y,
tex2, tex2x, tex2y):
"""
This draws a rectangle (textured with up to four textures) to the
screen.
Note that this is usually implemented in C code in the Ren'Py
module, and that this version is for debugging.
`sx`, `sy`
The location in the untransformed screen coordinate of the
upper-left corner of the drawing region. (Think of this as an
offset that is applied to coordinates.)
`x`, `y`
The location in the transformed coordinates to draw the
upper-left corner of the texture.
`w`, `h`
The width and height of texture.
`tex0`
The texture to bind to texture unit 0.
`tex0x`, `tex0y`
The coordinates within that texture of the upper-left corner.
`tex1...`, `tex2...`
Same, but for the other two textures.
`toff_...`
Texture offset to apply to the given side of the texture.
"""
gl.Disable(gl.POLYGON_SMOOTH)
# Pull apart the transform.
xdx = transform.xdx
xdy = transform.xdy
ydx = transform.ydx
ydy = transform.ydy
# Transform the vertex coordinates to screen-space.
x0 = (x + 0) * xdx + (y + 0) * xdy + sx
y0 = (x + 0) * ydx + (y + 0) * ydy + sy
x1 = (x + w) * xdx + (y + 0) * xdy + sx
y1 = (x + w) * ydx + (y + 0) * ydy + sy
x2 = (x + 0) * xdx + (y + h) * xdy + sx
y2 = (x + 0) * ydx + (y + h) * ydy + sy
x3 = (x + w) * xdx + (y + h) * xdy + sx
y3 = (x + w) * ydx + (y + h) * ydy + sy
# Compute the texture coordinates, and set up the textures.
if tex0 is not None:
has_tex0 = 1
gl.ActiveTextureARB(gl.TEXTURE0_ARB)
gl.BindTexture(gl.TEXTURE_2D, tex0.number)
xadd = tex0.xadd
yadd = tex0.yadd
xmul = tex0.xmul
ymul = tex0.ymul
t0u0 = xadd + xmul * (tex0x + 0)
t0u1 = xadd + xmul * (tex0x + w)
t0v0 = yadd + ymul * (tex0y + 0)
t0v1 = yadd + ymul * (tex0y + h)
else:
has_tex0 = 0
if tex1 is not None:
has_tex1 = 1
gl.ActiveTextureARB(gl.TEXTURE1_ARB)
gl.BindTexture(gl.TEXTURE_2D, tex1.number)
xadd = tex1.xadd
yadd = tex1.yadd
xmul = tex1.xmul
ymul = tex1.ymul
t1u0 = xadd + xmul * (tex1x + 0)
t1u1 = xadd + xmul * (tex1x + w)
t1v0 = yadd + ymul * (tex1y + 0)
t1v1 = yadd + ymul * (tex1y + h)
else:
has_tex1 = 0
if tex2 is not None:
has_tex2 = 1
gl.ActiveTextureARB(gl.TEXTURE2_ARB)
gl.BindTexture(gl.TEXTURE_2D, tex2.number)
xadd = tex2.xadd
yadd = tex2.yadd
xmul = tex2.xmul
ymul = tex2.ymul
t2u0 = xadd + xmul * (tex2x + 0)
t2u1 = xadd + xmul * (tex2x + w)
t2v0 = yadd + ymul * (tex2y + 0)
t2v1 = yadd + ymul * (tex2y + h)
else:
has_tex2 = 0
# Now, actually draw the textured rectangle.
gl.Begin(gl.TRIANGLE_STRIP)
if has_tex0:
gl.MultiTexCoord2fARB(gl.TEXTURE0_ARB, t0u0, t0v0)
if has_tex1:
gl.MultiTexCoord2fARB(gl.TEXTURE1_ARB, t1u0, t1v0)
if has_tex2:
gl.MultiTexCoord2fARB(gl.TEXTURE2_ARB, t2u0, t2v0)
gl.Vertex2f(x0, y0)
if has_tex0:
gl.MultiTexCoord2fARB(gl.TEXTURE0_ARB, t0u1, t0v0)
if has_tex1:
gl.MultiTexCoord2fARB(gl.TEXTURE1_ARB, t1u1, t1v0)
if has_tex2:
gl.MultiTexCoord2fARB(gl.TEXTURE2_ARB, t2u1, t2v0)
gl.Vertex2f(x1, y1)
if has_tex0:
gl.MultiTexCoord2fARB(gl.TEXTURE0_ARB, t0u0, t0v1)
if has_tex1:
gl.MultiTexCoord2fARB(gl.TEXTURE1_ARB, t1u0, t1v1)
if has_tex2:
gl.MultiTexCoord2fARB(gl.TEXTURE2_ARB, t2u0, t2v1)
gl.Vertex2f(x2, y2)
if has_tex0:
gl.MultiTexCoord2fARB(gl.TEXTURE0_ARB, t0u1, t0v1)
if has_tex1:
gl.MultiTexCoord2fARB(gl.TEXTURE1_ARB, t1u1, t1v1)
if has_tex2:
gl.MultiTexCoord2fARB(gl.TEXTURE2_ARB, t2u1, t2v1)
gl.Vertex2f(x3, y3)
gl.End()
C_DRAW = True
if C_DRAW:
if pysdlgl:
draw_rectangle = pysdlgl.draw_rectangle
else:
print "Warning: Draw not using C code."
+21 -62
View File
@@ -1,4 +1,3 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
@@ -30,8 +29,6 @@ import zipfile
import cStringIO
import threading
import pygame
# This is an entry in the image cache.
class CacheEntry(object):
@@ -85,10 +82,14 @@ class Cache(object):
# been pinned into memory.
self.pin_cache = { }
# Images that we tried, and failed, to preload.
self.preload_blacklist = set()
# The preload thread.
self.preload_thread = threading.Thread(target=self.preload_thread_main, name="preloader")
self.preload_thread.setDaemon(True)
self.preload_thread.start()
def quit(self):
if not self.preload_thread.isAlive():
@@ -107,6 +108,7 @@ class Cache(object):
def cache_limit(self):
return renpy.config.image_cache_size * renpy.config.screen_width * renpy.config.screen_height
# Clears out the cache.
def clear(self):
self.lock.acquire()
@@ -208,32 +210,9 @@ class Cache(object):
if renpy.config.debug_image_cache:
print "IC Added %r (%.02f%%)" % (ce.what, 100.0 * self.total_cache_size / self.cache_limit())
# RLE detection. (ce.size is used to check that we're not
# 0 pixels big.)
if id(ce.surf) not in rle_cache and ce.size:
renpy.display.draw.load_texture(ce.surf)
rle = not renpy.game.less_memory
if rle:
# We must copy the surface, so we have a RLE-specific version.
idsurf = id(ce.surf)
if idsurf in pin_rle_cache:
rle_surf = pin_rle_cache[idsurf]
else:
rle_surf = renpy.display.pgrender.copy_surface(ce.surf)
rle_surf.set_alpha(255, pygame.RLEACCEL)
renpy.display.render.mutated_surface(rle_surf)
rle_cache[idsurf] = rle_surf
if renpy.config.debug_image_cache:
print "Added to rle cache:", image
self.lock.release()
# Move it into the current generation. This isn't protected by
# a lock, so in certain circumstances we could have an
@@ -259,9 +238,6 @@ class Cache(object):
self.total_cache_size -= ce.size
del self.cache[ce.what]
if id(ce.surf) in rle_cache:
del rle_cache[id(ce.surf)]
if renpy.config.debug_image_cache:
print "IC Removed", ce.what
@@ -356,12 +332,12 @@ class Cache(object):
try:
image = self.preloads.pop(0)
if image not in preload_blacklist:
if image not in self.preload_blacklist:
try:
self.get(image)
except:
preload_blacklist.add(image)
self.preload_blacklist.add(image)
except:
pass
@@ -385,11 +361,7 @@ class Cache(object):
if renpy.config.debug_image_cache:
print "IC Pin Clear", image
idsurf = id(self.pin_cache[i])
if idsurf in pin_rle_cache:
del pin_rle_cache[idsurf]
surf = self.pin_cache[i]
del self.pin_cache[i]
@@ -397,7 +369,7 @@ class Cache(object):
# For each image in the worklist...
for image in workset:
if image in preload_blacklist:
if image in self.preload_blacklist:
continue
# If we have normal preloads, break out.
@@ -410,28 +382,14 @@ class Cache(object):
try:
surf = image.load()
self.pin_cache[image] = surf
rle_surf = renpy.display.pgrender.copy_surface(surf)
rle_surf.set_alpha(255, pygame.RLEACCEL)
pin_rle_cache[id(surf)] = rle_surf
except:
preload_blacklist.add(image)
renpy.display.draw.load_texture(surf)
# A map from id(cached surface) to rle version of cached surface.
rle_cache = { }
# Same thing, for pinned surfaces.
pin_rle_cache = { }
# Images that we tried, and failed, to preload.
preload_blacklist = set()
except:
self.preload_blacklist.add(image)
# The cache object.
cache = Cache()
def free_memory():
@@ -439,10 +397,9 @@ def free_memory():
Frees some memory.
"""
renpy.display.draw.free_memory()
cache.clear()
rle_cache.clear()
pin_rle_cache.clear()
class ImageBase(renpy.display.core.Displayable):
"""
@@ -491,10 +448,11 @@ class ImageBase(renpy.display.core.Displayable):
def render(self, w, h, st, at):
im = cache.get(self)
texture = renpy.display.draw.load_texture(im)
w, h = im.get_size()
rv = renpy.display.render.Render(w, h)
rv.blit(im, (0, 0))
rv.blit(texture, (0, 0))
return rv
def predict_one(self, callback):
@@ -1494,4 +1452,5 @@ def load_image(fn):
This loads an image from the given filename, using the cache.
"""
return cache.get(image(fn))
surf = cache.get(image(fn))
return renpy.display.draw.load_texture(surf)
+6 -35
View File
@@ -26,7 +26,6 @@
import renpy
from renpy.display.render import render, Render
Image = renpy.display.im.image
def wrap_render(child, w, h, st, at):
@@ -34,33 +33,6 @@ def wrap_render(child, w, h, st, at):
rv = Render(rend.width, rend.height)
rv.blit(rend, (0, 0))
return rv
class UncachedImage(renpy.display.core.Displayable):
"""
An image that is loaded immediately and not cached.
"""
def __init__(self, file, hint=None, scale=None, style='image_placement',
**properties):
super(UncachedImage, self).__init__(style=style, **properties)
self.surf = renpy.display.pgrender.load_image(file, hint)
if scale:
renpy.display.render.blit_lock.acquire()
self.surf = renpy.display.pgrender.transform_scale(self.surf, scale)
renpy.display.render.blit_lock.release()
renpy.display.render.mutated_surface(self.surf)
def render(self, w, h, st, at):
sw, sh = self.surf.get_size()
rv = renpy.display.render.Render(sw, sh)
rv.blit(self.surf, (0, 0))
return rv
class ImageReference(renpy.display.core.Displayable):
"""
@@ -83,9 +55,9 @@ class ImageReference(renpy.display.core.Displayable):
self.name = name
def get_parameterized(self):
def _get_parameterized(self):
if self.param_target:
return self.param_target.get_parameterized()
return self.param_target._get_parameterized()
return self
@@ -140,19 +112,17 @@ class ImageReference(renpy.display.core.Displayable):
return False
def hide(self, st, at):
def _hide(self, st, at, kind):
if not self.target:
self.find_target()
return self.target.hide(st, at)
return self.target._hide(st, at, kind)
def set_transform_event(self, event):
if not self.target:
self.find_target()
return self.target.set_transform_event(event)
def event(self, ev, x, y, st):
if not self.target:
@@ -281,7 +251,8 @@ class Frame(renpy.display.core.Displayable):
def visit(self):
return [ self.image ]
class ImageButton(renpy.display.behavior.Button):
"""
Used to implement the guts of an image button.
+107 -39
View File
@@ -169,7 +169,6 @@ class Container(renpy.display.core.Displayable):
return None
def visit(self):
return self.children
@@ -178,23 +177,14 @@ class Container(renpy.display.core.Displayable):
def __enter__(self):
if renpy.ui.current is self and not renpy.ui.current_once:
return self
raise Exception("%r cannot be used as a context manager.", type(self).__name__)
renpy.ui.context_enter(self)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
return False
if renpy.ui.current is not self:
raise Exception("Widget %r left open at end of block.")
renpy.ui.close()
renpy.ui.context_exit(self)
return False
@@ -317,7 +307,7 @@ class Grid(Container):
def __init__(self, cols, rows, padding=None,
transpose=False,
style='default', **properties):
style='grid', **properties):
"""
@param cols: The number of columns in this widget.
@@ -343,9 +333,12 @@ class Grid(Container):
cols = self.cols
rows = self.rows
if len(self.children) != cols * rows:
raise Exception("Grid not completely full.")
if len(self.children) != cols * rows:
if len(self.children) < cols * rows:
raise Exception("Grid not completely full.")
else:
raise Exception("Grid overfull.")
# If necessary, transpose the grid (kinda hacky, but it works here.)
if self.transpose:
self.transpose = False
@@ -404,6 +397,14 @@ class Grid(Container):
return rv
class IgnoreLayers(Exception):
"""
Raise this to have the event ignored by layers, but reach the
underlay.
"""
pass
class MultiBox(Container):
layer_name = None
@@ -436,8 +437,9 @@ class MultiBox(Container):
self.anim_times.append(anim_time)
def append_scene_list(self, l):
for tag, zo, start, anim, d in l:
self.add(d, start, anim)
for sle in l:
self.add(sle.displayable, sle.show_time, sle.animation_time)
if self.scene_list is None:
self.scene_list = [ ]
@@ -496,19 +498,34 @@ class MultiBox(Container):
if layout == "fixed":
self.offsets = [ ]
rv = renpy.display.render.Render(width, height, layer_name=self.layer_name)
rv = None
surfaces = [ ]
for child, cst, cat in zip(self.children, csts, cats):
surf = render(child, width, height, cst, cat)
if rv is None:
if self.style.fit_first:
sw, sh = surf.get_size()
width = min(width, sw)
height = min(height, sh)
rv = renpy.display.render.Render(width, height, layer_name=self.layer_name)
if surf:
offset = child.place(rv, 0, 0, width, height, surf)
self.offsets.append(offset)
else:
self.offsets.append((0, 0))
if rv is None:
rv = renpy.display.render.Render(width, height, layer_name=self.layer_name)
return rv
if layout == "horizontal":
@@ -637,16 +654,24 @@ class MultiBox(Container):
children_offsets = zip(self.children, self.offsets, self.start_times)
children_offsets.reverse()
for i, (xo, yo), t in children_offsets:
try:
for i, (xo, yo), t in children_offsets:
if t is None:
cst = st
if t is None:
cst = st
else:
cst = renpy.game.interface.event_time - t
rv = i.event(ev, x - xo, y - yo, cst)
if rv is not None:
return rv
except IgnoreLayers:
if self.layers:
return None
else:
cst = renpy.game.interface.event_time - t
rv = i.event(ev, x - xo, y - yo, cst)
if rv is not None:
return rv
raise
return None
@@ -823,6 +848,7 @@ class DynamicDisplayable(renpy.display.core.Displayable):
self.child = None
def __init__(self, function, *args, **kwargs):
super(DynamicDisplayable, self).__init__()
self.child = None
@@ -865,8 +891,12 @@ class DynamicDisplayable(renpy.display.core.Displayable):
i.predict(callback)
def get_placement(self):
if not self.child:
self.child, redraw = self.function(0, 0, *self.args, **self.kwargs)
return self.child.get_placement()
def event(self, ev, x, y, st):
if self.child:
return self.child.event(ev, x, y, st)
@@ -939,8 +969,8 @@ def ShowingSwitch(*args, **kwargs):
class IgnoresEvents(Container):
def __init__(self, child):
super(IgnoresEvents, self).__init__(style='default')
def __init__(self, child, **properties):
super(IgnoresEvents, self).__init__(**properties)
self.add(child)
def render(self, w, h, st, at):
@@ -957,8 +987,6 @@ class IgnoresEvents(Container):
# Ignores events.
def event(self, ev, x, y, st):
return None
class Viewport(Container):
@@ -985,6 +1013,7 @@ class Viewport(Container):
mousewheel=False,
draggable=False,
style='viewport',
replaces=None,
**properties):
super(Viewport, self).__init__(style=style, **properties)
@@ -1001,6 +1030,16 @@ class Viewport(Container):
else:
self.yadjustment = yadjustment
if isinstance(replaces, Viewport):
self.xadjustment.value = replaces.xadjustment.value
self.yadjustment.value = replaces.yadjustment.value
if self.xadjustment.adjustable is None:
self.xadjustment.adjustable = True
if self.yadjustment.adjustable is None:
self.yadjustment.adjustable = True
self.set_adjustments = set_adjustments
self.child_width, self.child_height = child_size
@@ -1010,7 +1049,7 @@ class Viewport(Container):
self.width = 0
self.height = 0
def per_interact(self):
self.xadjustment.register(self)
self.yadjustment.register(self)
@@ -1133,7 +1172,7 @@ class Side(Container):
def after_setstate(self):
self.sized = False
def __init__(self, positions, style='default', **properties):
def __init__(self, positions, style='side', **properties):
super(Side, self).__init__(style=style, **properties)
@@ -1321,8 +1360,8 @@ class Alpha(renpy.display.core.Displayable):
class AdjustTimes(Container):
def __init__(self, child, start_time, anim_time):
super(AdjustTimes, self).__init__(style='default')
def __init__(self, child, start_time, anim_time, **properties):
super(AdjustTimes, self).__init__(**properties)
self.start_time = start_time
self.anim_time = anim_time
@@ -1353,3 +1392,32 @@ class AdjustTimes(Container):
return self.child.get_placement()
class LiveTile(Container):
"""
:doc: other
Tiles the `child` displayable until it fills the area allocated to
this displayable.
The size of the displayable can be set with the :propref:`xmaximum` and
:propref:`ymaximum` style properties.
"""
def __init__(self, child, style='tile', **properties):
super(LiveTile, self).__init__(style=style, **properties)
self.add(child)
def render(self, width, height, st, at):
cr = renpy.display.render.render(self.child, width, height, st, at)
cw, ch = cr.get_size()
rv = renpy.display.render.Render(width, height)
for y in range(0, height, ch):
for x in range(0, width, cw):
rv.blit(cr, (x, y), focus=False)
return rv
+2 -2
View File
@@ -245,8 +245,8 @@ transform = _renpy.transform
blend = _renpy.blend
def imageblend(a, b, dst, img, amap):
red = byte_offset(img)[0]
_renpy.imageblend(a, b, dst, img, red, amap)
alpha = byte_offset(img)[3]
_renpy.imageblend(a, b, dst, img, alpha, amap)
def colormatrix(src, dst, matrix):
+492 -388
View File
File diff suppressed because it is too large Load Diff
+39 -2
View File
@@ -19,8 +19,9 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This module deals with pygame-specific rendering tasks.
# This module wraps the pygame surface class (and associated functions).
import sys
import pygame
import renpy
@@ -57,15 +58,51 @@ def set_mode(resolution, flags=0, depth=0):
sample_noalpha = s.convert(rv)
return rv
set_mode_unscaled = set_mode
def set_bgra_masks():
"""
This rebuilds the sample surfaces, to ones that use the given
masks.
"""
# Annoyingly, the value for the big mask seems to vary from
# platform to platform. So we read it out of a surface.
global sample_alpha
global sample_noalpha
# Create a sample surface.
s = opygame.Surface((10, 10), 0, 32)
sample_alpha = s.convert_alpha()
# Sort the compoents by absolute value.
masks = list(sample_alpha.get_masks())
masks.sort(key=lambda a : abs(a))
# Choose the masks.
if sys.byteorder == 'little':
masks = ( masks[2], masks[1], masks[0], masks[3] )
else:
masks = ( masks[1], masks[2], masks[3], masks[0] )
# Create the sample surface.
sample_alpha = opygame.Surface((10, 10), 0, 32, masks)
sample_noalpha = opygame.Surface((10, 10), 0, 32, masks[:3] + (0,))
class Surface(opygame.Surface):
"""
This allows us to wrap around pygame's surface, to change
its mode, as necessary.
"""
opaque = False
def is_opaque(self):
return self.opaque
def convert_alpha(self, surface=None):
return copy_surface_unscaled(self, True)
-1
View File
@@ -46,7 +46,6 @@ def start(gamedir):
break
else:
return
try:
import subprocess
+221 -631
View File
File diff suppressed because it is too large Load Diff
+16 -6
View File
@@ -172,9 +172,11 @@ def load_scaling():
scaling_loaded = True
# Once we load scaling, GL mode won't work. So let's kill it off here.
renpy.config.gl_enable = False
def real(s):
return s.surface
def same_size(*args):
"""
@@ -366,10 +368,14 @@ def load_scaling():
def copy(self):
return ScaledSurface(self.surface.copy(), wh=self.get_size())
def convert(self):
return ScaledSurface(self.surface.convert(), wh=self.get_size())
def convert_alpha(self):
return ScaledSurface(self.surface.convert_alpha(), wh=self.get_size())
def fill(self, color):
self.surface.fill(color)
def get_alpha(self):
return self.surface.get_alpha()
@@ -488,10 +494,14 @@ def load_scaling():
pygame.display.update = update
old_get_surface = pygame.display.get_surface
def get_surface():
return screen
if old_get_surface():
return screen
else:
return None
pygame.display.get_surface = get_surface
@@ -533,7 +543,7 @@ def load_scaling():
def rotozoom(surf, angle, scale):
new_surf = pgrender.rotozoom(surf.surface, angle, scale)
new_surf = pgrender.rotozoom_unscaled(surf.surface, angle, scale)
return ScaledSurface(new_surf)
pgrender.rotozoom = rotozoom
+484
View File
@@ -0,0 +1,484 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import renpy
class Screen(renpy.object.Object):
"""
A screen is a collection of widgets that are displayed together.
This class stores information about the screen.
"""
def __init__(self,
name,
function,
modal="False",
zorder="0",
tag=None,
predict_function=None):
# The name of this screen.
if isinstance(name, basestring):
name = tuple(name.split())
self.name = name
screens[name] = self
# The function that is called to display this screen.
self.function = function
# The function that is called to predict the images that
# will be used by the screen.
self.predict_function = predict_function
# Expression: Are we modal? (A modal screen ignores screens under it.)
self.modal = modal
# Expression: Our zorder.
self.zorder = zorder
# The tag associated with the screen.
self.tag = tag or name[0]
class ScreenDisplayable(renpy.display.layout.Container):
"""
A screen is a collection of widgets that are displayed together. This
class is responsible for managing the display of a screen.
"""
no_save = [ 'screen' ]
def after_setstate(self):
self.screen = screens[self.screen_name]
def __init__(self, screen, tag, layer, widget_properties={}, scope={}, **properties):
super(ScreenDisplayable, self).__init__(**properties)
# Stasgh the properties, so we can re-create the screen.
self.properties = properties
# The screen, and it's name. (The name is used to look up the
# screen on save.)
self.screen = screen
self.screen_name = screen.name
# The tag and layer screen was displayed with.
self.tag = tag
self.layer = layer
# The scope associated with this statement. This is passed in
# as keyword arguments to the displayable.
self.scope = renpy.python.RevertableDict(scope)
# The child associated with this screen.
self.child = None
# Widget properties given to this screen the last time it was
# shown.
self.widget_properties = widget_properties
# A map from name to the widget with that name.
self.widgets = { }
old_screen = get_screen(tag, layer)
# A map from name to the transform with that name. (This is
# taken from the old version of the screen, if it exists.
if old_screen is not None:
self.transforms = old_screen.transforms
else:
self.transforms = { }
# What widgets and transforms were the last time this screen was
# updated. Used to communicate with the ui module, and only
# valid during an update - not used at other times.
self.old_widgets = None
self.old_transforms = None
# Should we transfer data from the old_screen? This becomes
# true once this screen finishes updating for the first time,
# and also while we're using something.
self.old_transfers = (old_screen and old_screen.screen_name == self.screen_name)
# The current transform event, and the last transform event to
# be processed.
self.current_transform_event = None
# A dict-set of widgets (by id) that have been hidden from us.
self.hidden_widgets = { }
# Are we hiding?
self.hiding = False
# Modal and zorder.
self.modal = renpy.python.py_eval(self.screen.modal, locals=self.scope)
self.zorder = renpy.python.py_eval(self.screen.zorder, locals=self.scope)
def __repr__(self):
return "<ScreenDisplayable: %r>" % (self.screen_name,)
def visit(self):
return [ self.child ]
def per_interact(self):
renpy.display.render.redraw(self, 0)
self.update()
def set_transform_event(self, event):
super(ScreenDisplayable, self).set_transform_event(event)
self.current_transform_event = event
def find_focusable(self, callback, focus_name):
if self.child and not self.hiding:
self.child.find_focusable(callback, focus_name)
def _hide(self, st, at, kind):
if self.hiding:
hid = self
else:
hid = ScreenDisplayable(self.screen, self.tag, self.layer, self.widget_properties, self.scope, **self.properties)
hid.transforms = self.transforms.copy()
hid.widgets = self.widgets.copy()
hid.old_transfers = True
hid.hiding = True
hid.current_transform_event = kind
hid.update()
renpy.display.render.redraw(hid, 0)
rv = None
# Compute the reverse of transforms and widgets.
reverse_transforms = dict((id(v), k) for k, v in hid.transforms.iteritems())
reverse_widgets = dict((id(v), k) for k, v in hid.widgets.iteritems())
# Assumption: the only displayables that can keep us around
# are Transforms that handle hide.
# Iterate over our immediate children, trying to hide them.
for d in list(hid.child.children):
id_d = id(d)
# If we have a transform, call its _hide method. If that comes
# back non-None, store the new transform, and keep us alive.
#
# Otherwise, remove the child.
name = reverse_transforms.get(id_d, None)
if name is not None:
c = d._hide(st, at, kind)
if c is not None:
hid.transforms[name] = c
rv = hid
else:
hid.hidden_widgets[name] = True
hid.child.remove(d)
continue
# Remove any non-transform children.
name = reverse_widgets.get(id_d, None)
if name is not None:
hid.hidden_widgets[name] = True
hid.child.remove(d)
return rv
def update(self):
# Update _current_screen
global _current_screen
old_screen = _current_screen
_current_screen = self
# Cycle widgets and transforms.
self.old_widgets = self.widgets
self.old_transforms = self.transforms
self.widgets = { }
self.transforms = { }
# Render the child.
old_ui_screen = renpy.ui.screen
renpy.ui.screen = self
renpy.ui.detached()
self.child = renpy.ui.fixed()
self.children = [ self.child ]
self.scope["_scope"] = self.scope
self.scope["_name"] = 0
self.screen.function(**self.scope)
renpy.ui.close()
renpy.ui.screen = old_ui_screen
_current_screen = old_screen
# Visit all the children, to get them started.
self.child.visit_all(lambda c : c.per_interact())
# Finish up.
self.old_widgets = None
self.old_transforms = None
self.old_transfers = True
if self.current_transform_event:
for i in self.child.children:
i.set_transform_event(self.current_transform_event)
self.current_transform_event = None
return self.widgets
def render(self, w, h, st, at):
if not self.child:
self.update()
child = renpy.display.render.render(self.child, w, h, st, at)
rv = renpy.display.render.Render(w, h)
rv.blit(child, (0, 0), focus=not self.hiding, main=not self.hiding)
rv.modal = self.modal and not self.hiding
return rv
def get_placement(self):
if not self.child:
self.update()
return self.child.get_placement()
def event(self, ev, x, y, st):
if self.hiding:
return
global _current_screen
old_screen = _current_screen
_current_screen = self
rv = self.child.event(ev, x, y, st)
_current_screen = old_screen
if rv is not None:
return rv
if self.modal:
raise renpy.display.layout.IgnoreLayers()
# The name of the screen that is currently being displayed, or
# None if no screen is being currently displayed.
_current_screen = None
# A map from screen name to screen object.
screens = { }
def define_screen(*args, **kwargs):
"""
:doc: screens
:args: (name, function, modal="False", zorder="0", tag=None)
Defines a screen with `name`, which should be a string.
`function`
The function that is called to display the screen. The
function is called with the screen scope as keyword
arguments. It should ignore additional keyword arguments.
The function should call the ui functions to add things to the
screen.
`modal`
A string that, when evaluated, determines of the created
screen should be modal. A modal screen prevents screens
underneath it from receiving input events.
`zorder`
A string that, when evaluated, should be an integer. The integer
controls the order in which screens are displayed. A screen
with a greater zorder number is displayed above screens with a
lesser zorder number.
`tag`
The tag associated with this screen. When the screen is shown,
it replaces any other screen with the same tag. The tag
defaults to the name of the screen.
"""
Screen(*args, **kwargs)
def get_screen(name, layer="screens"):
"""
:doc: screens
Returns the ScreenDisplayable with the given `tag`, on
`layer`. If no displayable with the tag is not found, it is
interpreted as screen name. If it's still not found, None is returned.
"""
if isinstance(name, basestring):
name = tuple(name.split())
tag = name[0]
sl = renpy.exports.scene_lists()
sd = sl.get_displayable_by_tag(layer, tag)
if sd is None:
sd = sl.get_displayable_by_name(layer, name)
return sd
def has_screen(name):
"""
Returns true if a screen with the given name exists.
"""
if not isinstance(name, tuple):
name = tuple(name.split())
return name in screens
def show_screen(_screen_name, _layer='screens', _tag=None, _widget_properties={}, _transient=False, **kwargs):
"""
:doc: screens
The programmatic equivalent of the show screen statement.
Shows the named screen.
`_screen_name`
The name of the screen to show.
`_layer`
The layer to show the screen on.
`_tag`
The tag to show the screen with. If not specified, defaults to
the tag associated with the screen. It that's not specified,
defaults to the name of the screen.,
`_widget_properties`
A map from the id of a widget to a property name -> property
value map. When a widget with that id is shown by the screen,
the specified properties are added to it.
`_transient`
If true, the screen will be automatically hidden at the end of
the current interaction.
Keyword arguments not beginning with underscore (_) are used to
initialize the screen's scope.
"""
name = _screen_name
if not isinstance(name, tuple):
name = tuple(name.split())
if not name in screens:
raise Exception("Screen %s is not known.\n" % (name[0],))
screen = screens[name]
if _tag is None:
_tag = screen.tag
d = ScreenDisplayable(screen, _tag, _layer, _widget_properties, kwargs)
renpy.exports.show(name, tag=_tag, what=d, layer=_layer, zorder=d.zorder, transient=_transient, munge_name=False)
def hide_screen(tag, layer='screens'):
"""
:doc: screens
The programmatic equivalent of the hide screen statement.
Hides the screen with `tag` on `layer`.
"""
screen = get_screen(tag, layer)
if screen is not None:
renpy.exports.hide(screen.tag, layer=layer)
def use_screen(_screen_name, _name=(), **kwargs):
name = _screen_name
if not isinstance(name, tuple):
name = tuple(name.split())
if name not in screens:
raise Exception("Screen %r is not known." % name)
old_transfers = _current_screen.old_transfers
_current_screen.old_transfers = True
screen = screens[name]
scope = kwargs["_scope"].copy() or { }
scope.update(kwargs)
scope["_scope"] = scope
scope["_name"] = (_name, name)
screen.function(**scope)
_current_screen.old_transfers = old_transfers
def current_screen():
return _current_screen
def get_widget(screen, id, layer='screens'):
"""
:doc: screens
From the `screen` on `layer`, returns the widget with
`id`. Returns None if the screen doesn't exist, or there is no
widget with that id on the screen.
"""
if screen is None:
screen = current_screen()
else:
screen = get_screen(screen, layer)
if not isinstance(screen, ScreenDisplayable):
return None
if screen.child is None:
screen.update()
rv = screen.widgets.get(id, None)
return rv
+989
View File
@@ -0,0 +1,989 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import renpy
import pygame
import math
import weakref
import time
from renpy.display.render import blit_lock, IDENTITY, BLIT, DISSOLVE, IMAGEDISSOLVE, PIXELLATE
# A map from cached surface to rle version of cached surface.
rle_cache = weakref.WeakKeyDictionary()
class Clipper(object):
"""
This is used to calculate the clipping rectangle and update rectangles
used for a particular draw of the screen.
"""
def __init__(self):
# Lists of (x0, y0, x1, y1, clip, surface, transform) tuples,
# representing how a displayable is drawn to the screen.
self.blits = [ ]
self.old_blits = [ ]
# Sets of (x0, y0, x1, y1) tuples, representing areas that
# aren't part of any displayable.
self.forced = set()
self.old_forced = set()
# The set of surfaces that have been mutated recently.
self.mutated = set()
def compute(self, full_redraw):
"""
This returns a clipping rectangle, and a list of update rectangles
that cover the changes between the old and new frames.
"""
# First, get things out of the fields, and update them. This
# allows us to just return without having to do any cleanup
# code.
bl0 = self.old_blits
bl1 = self.blits
old_forced = self.old_forced
forced = self.forced
mutated = self.mutated
self.old_blits = bl1
self.blits = [ ]
self.old_forced = forced
self.forced = set()
self.mutated = set()
sw = renpy.config.screen_width
sh = renpy.config.screen_height
sa = sw * sh
# A tuple representing the size of the fullscreen.
fullscreen = (0, 0, sw, sh)
# Check to see if a full redraw has been forced, and return
# early.
if full_redraw:
return fullscreen, [ fullscreen ]
# Quick checks to see if a dissolve is happening, or something like
# that.
changes = forced | old_forced
if fullscreen in changes:
return fullscreen, [ fullscreen ]
# Compute the differences between the two sets, and add those
# to changes.
i0 = 0
i1 = 0
bl1set = set(bl1)
while True:
if i0 >= len(bl0) or i1 >= len(bl1):
break
b0 = bl0[i0]
b1 = bl1[i1]
if b0 == b1:
if id(b0[5]) in mutated:
changes.add(b0[:5])
i0 += 1
i1 += 1
elif b0 not in bl1set:
changes.add(b0[:5])
i0 += 1
else:
changes.add(b1[:5])
i1 += 1
changes.update(i[:5] for i in bl0[i0:])
changes.update(i[:5] for i in bl1[i1:])
# No changes? Quit.
if not changes:
return None, [ ]
# Compute the sizes of the updated rectangles.
sized = [ ]
for x0, y0, x1, y1, (sx0, sy0, sx1, sy1) in changes:
if x0 < sx0:
x0 = sx0
if y0 < sy0:
y0 = sy0
if x1 > sx1:
x1 = sx1
if y1 > sy1:
y1 = sy1
w = x1 - x0
h = y1 - y0
if w <= 0 or h <= 0:
continue
area = w * h
if area >= sa:
return fullscreen, [ fullscreen ]
sized.append((area, x0, y0, x1, y1))
sized.sort()
# The list of non-contiguous updates.
noncont = [ ]
# The total area of noncont.
nca = 0
# Pick the largest area, merge with all overlapping smaller areas, repeat
# until no merge possible.
while sized:
area, x0, y0, x1, y1 = sized.pop()
merged = False
if nca + area >= sa:
return (0, 0, sw, sh), [ (0, 0, sw, sh) ]
i = 0
while i < len(sized):
iarea, ix0, iy0, ix1, iy1 = sized[i]
if (x0 <= ix0 <= x1 or x0 <= ix1 <= x1) and \
(y0 <= iy0 <= y1 or y0 <= iy1 <= y1):
merged = True
x0 = min(x0, ix0)
x1 = max(x1, ix1)
y0 = min(y0, iy0)
y1 = max(y1, iy1)
area = (x1 - x0) * (y1 - y0)
sized.pop(i)
else:
i += 1
if merged:
sized.append((area, x0, y0, x1, y1))
else:
noncont.append((x0, y0, x1, y1))
nca += area
if not noncont:
return None, [ ]
x0, y0, x1, y1 = noncont.pop()
x0 = int(x0)
y0 = int(y0)
x1 = int(math.ceil(x1))
y1 = int(math.ceil(y1))
# A list of (x, y, w, h) tuples for each update.
updates = [ (x0, y0, x1 - x0, y1 - y0) ]
for ix0, iy0, ix1, iy1 in noncont:
ix0 = int(ix0)
iy0 = int(iy0)
ix1 = int(math.ceil(ix1))
iy1 = int(math.ceil(iy1))
x0 = min(x0, ix0)
y0 = min(y0, iy0)
x1 = max(x1, ix1)
y1 = max(y1, iy1)
updates.append((ix0, iy0, ix1 - ix0, iy1 - iy0))
return (x0, y0, x1 - x0, y1 - y0), updates
clippers = [ Clipper() ]
def draw_special(what, dest, x, y):
"""
This handles the special drawing operations, such as dissolve and
image dissolve. `x` and `y` are the offsets of the thing to be drawn
relative to the destination rectangle, and are always negative.
"""
dw, dh = dest.get_size()
w = min(dw, what.width + x)
h = min(dh, what.height + y)
if w <= 0 or h <= 0:
return
if what.operation == DISSOLVE:
bottom = what.children[0][0].render_to_texture(True)
top = what.children[1][0].render_to_texture(True)
if what.operation_alpha:
target = renpy.display.pgrender.surface((w, h), True)
else:
target = dest.subsurface((0, 0, w, h))
renpy.display.module.blend(
bottom.subsurface((-x, -y, w, h)),
top.subsurface((-x, -y, w, h)),
target,
int(what.operation_complete * 255))
if what.operation_alpha:
dest.blit(target, (0, 0))
elif what.operation == IMAGEDISSOLVE:
image = what.children[0][0].render_to_texture(True)
bottom = what.children[1][0].render_to_texture(True)
top = what.children[2][0].render_to_texture(True)
if what.operation_alpha:
target = renpy.display.pgrender.surface((w, h), True)
else:
target = dest.subsurface((0, 0, w, h))
ramplen = what.operation_parameter
ramp = "\x00" * 256
for i in xrange(0, ramplen):
ramp += chr(255 * i / ramplen)
ramp += "\xff" * 256
step = int( what.operation_complete * (256 + ramplen) )
ramp = ramp[step:step+256]
renpy.display.module.imageblend(
bottom.subsurface((-x, -y, w, h)),
top.subsurface((-x, -y, w, h)),
target,
image.subsurface((-x, -y, w, h)),
ramp)
if what.operation_alpha:
dest.blit(target, (0, 0))
elif what.operation == PIXELLATE:
surf = what.children[0][0].render_to_texture(False)
px = what.operation_parameter
renpy.display.module.pixellate(
surf.subsurface((-x, -y, w, h)),
dest.subsurface((0, 0, w, h)),
px, px, px, px)
else:
raise Exception("Unknown operation: %d" % what.operation)
def draw(dest, clip, what, xo, yo, screen):
"""
This is the simple draw routine, which only works when alpha is 1.0
and the matrices are None. If those aren't the case, draw_complex
is used instead.
`dest` - Either a destination surface, or a clipper.
`clip` - If None, we should draw. Otherwise we should clip, and this is
the rectangle to clip to.
`what` - The Render or Surface we're drawing to.
`xo` - The X offset.
`yo` - The Y offset.
`screen` - True if this is a blit to the screen, False otherwise.
"""
if not isinstance(what, renpy.display.render.Render):
# Pixel-Aligned blit.
if isinstance(xo, int) and isinstance(yo, int):
if screen:
what = rle_cache.get(what, what)
if clip:
w, h = what.get_size()
dest.blits.append((xo, yo, xo + w, yo + h, clip, what, None))
else:
try:
blit_lock.acquire()
dest.blit(what, (xo, yo))
finally:
blit_lock.release()
# Subpixel blit.
else:
if clip:
w, h = what.get_size()
dest.blits.append((xo, yo, xo + w, yo + h, clip, what, None))
else:
renpy.display.module.subpixel(what, dest, xo, yo)
return
# Deal with draw functions.
if what.operation != BLIT:
xo = int(xo)
yo = int(yo)
if clip:
dx0, dy0, dx1, dy1 = clip
dw = dx1 - dx0
dh = dy1 - dy0
else:
dw, dh = dest.get_size()
if xo >= 0:
newx = 0
subx = xo
else:
newx = xo
subx = 0
if yo >= 0:
newy = 0
suby = yo
else:
newy = yo
suby = 0
if subx >= dw or suby >= dh:
return
# newx and newy are the offset of this render relative to the
# subsurface. They can only be negative or 0, as otherwise we
# would make a smaller subsurface.
subw = min(dw - subx, what.width + newx)
subh = min(dh - suby, what.height + newy)
if subw <= 0 or subh <= 0:
return
if clip:
dest.forced.add((subx, suby, subx + subw, suby + subh, clip))
else:
newdest = dest.subsurface((subx, suby, subw, subh))
# what.draw_func(newdest, newx, newy)
draw_special(what, newdest, newx, newy)
return
# Deal with clipping, if necessary.
if what.clipping:
if clip:
cx0, cy0, cx1, cy1 = clip
cx0 = max(cx0, xo)
cy0 = max(cy0, yo)
cx1 = min(cx1, xo + what.width)
cy1 = min(cy1, yo + what.height)
if cx0 > cx1 or cy0 > cy1:
return
clip = (cx0, cy0, cx1, cy1)
else:
# After this code, x and y are the coordinates of the subsurface
# relative to the destination. xo and yo are the offset of the
# upper-left corner relative to the subsurface.
if xo >= 0:
x = xo
xo = 0
else:
x = 0
# xo = xo
if yo >= 0:
y = yo
yo = 0
else:
y = 0
# yo = yo
dw, dh = dest.get_size()
width = min(dw - x, what.width + xo)
height = min(dh - y, what.height + yo)
if width < 0 or height < 0:
return
dest = dest.subsurface((x, y, width, height))
# Deal with alpha and transforms by passing them off to draw_transformed.
if what.alpha != 1 or what.forward:
for child, cxo, cyo, focus, main in what.visible_children:
draw_transformed(dest, clip, child, xo + cxo, yo + cyo,
what.alpha, what.forward, what.reverse)
return
for child, cxo, cyo, focus, main in what.visible_children:
draw(dest, clip, child, xo + cxo, yo + cyo, screen)
def draw_transformed(dest, clip, what, xo, yo, alpha, forward, reverse):
# If our alpha has hit 0, don't do anything.
if alpha <= 0.003: # (1 / 256)
return
if forward is None:
forward = IDENTITY
reverse = IDENTITY
if not isinstance(what, renpy.display.render.Render):
# Figure out where the other corner of the transformed surface
# is on the screen.
sw, sh = what.get_size()
if clip:
dx0, dy0, dx1, dy1 = clip
dw = dx1 - dx0
dh = dy1 - dy0
else:
dw, dh = dest.get_size()
x0, y0 = 0.0, 0.0
x1, y1 = reverse.transform(sw, 0.0)
x2, y2 = reverse.transform(sw, sh)
x3, y3 = reverse.transform(0.0, sh)
minx = math.floor(min(x0, x1, x2, x3) + xo)
maxx = math.ceil(max(x0, x1, x2, x3) + xo)
miny = math.floor(min(y0, y1, y2, y3) + yo)
maxy = math.ceil(max(y0, y1, y2, y3) + yo)
if minx < 0:
minx = 0
if miny < 0:
miny = 0
if maxx > dw:
maxx = dw
if maxy > dh:
maxy = dh
if minx > dw or miny > dh:
return
cx, cy = forward.transform(minx - xo, miny - yo)
if clip:
dest.blits.append(
(minx, miny, maxx + dx0, maxy + dy0, clip, what,
(cx, cy,
forward.xdx, forward.ydx,
forward.xdy, forward.ydy,
alpha)))
else:
dest = dest.subsurface((minx, miny, maxx - minx, maxy - miny))
renpy.display.module.transform(
what, dest,
cx, cy,
forward.xdx, forward.ydx,
forward.xdy, forward.ydy,
alpha, True)
return
if what.clipping:
if reverse.xdy or reverse.ydx:
draw_transformed(dest, clip, what.pygame_surface(True), xo, yo, alpha, forward, reverse)
return
# raise Exception("Non-axis-aligned clipping is not supported.")
width = what.width * reverse.xdx
height = what.height * reverse.ydy
if clip:
cx0, cy0, cx1, cy1 = clip
cx0 = max(cx0, xo)
cy0 = max(cy0, yo)
cx1 = min(cx1, xo + width)
cy1 = min(cy1, yo + height)
if cx0 > cx1 or cy0 > cy1:
return
clip = (cx0, cy0, cx1, cy1)
else:
# After this code, x and y are the coordinates of the subsurface
# relative to the destination. xo and yo are the offset of the
# upper-left corner relative to the subsurface.
if xo >= 0:
x = xo
xo = 0
else:
x = 0
# xo = xo
if yo >= 0:
y = yo
yo = 0
else:
y = 0
# yo = yo
dw, dh = dest.get_size()
width = min(dw - x, width + xo)
height = min(dh - y, height + yo)
if width < 0 or height < 0:
return
dest = dest.subsurface((x, y, width, height))
if what.draw_func:
child = what.pygame_surface(True)
draw_transformed(dest, clip, child, xo, yo, alpha, forward, reverse)
# raise Exception("Using a draw_func on a transformed surface is not supported.")
for child, cxo, cyo, focus, main in what.visible_children:
cxo, cyo = reverse.transform(cxo, cyo)
if what.forward:
child_forward = forward * what.forward
child_reverse = what.reverse * reverse
else:
child_forward = forward
child_reverse = reverse
draw_transformed(dest, clip, child, xo + cxo, yo + cyo, alpha * what.alpha, child_forward, child_reverse)
def do_draw_screen(screen_render, full_redraw):
"""
Draws the render produced by render_screen to the screen.
"""
yoffset = xoffset = 0
screen_render.is_opaque()
clip = (xoffset, yoffset, xoffset + screen_render.width, yoffset + screen_render.height)
clipper = clippers[0]
draw(clipper, clip, screen_render, xoffset, yoffset, True)
cliprect, updates = clipper.compute(full_redraw)
if cliprect is None:
return [ ]
x, y, w, h = cliprect
dest = pygame.display.get_surface().subsurface(cliprect)
draw(dest, None, screen_render, -x, -y, True)
return updates
class SWDraw(object):
"""
This uses the software renderer to draw to the screen.
"""
def __init__(self):
# Should we draw the screen?
self.suppressed_blit = False
# The earliest time at which the next frame can be redrawn.
self.next_frame = 0
# Mouse re-drawing.
self.mouse_location = None
self.mouse_backing = None
self.mouse_backing_pos = None
self.mouse_info = None
# Is the mouse currently visible?
self.mouse_old_visible = None
# This is used to cache the surface->texture operation.
self.texture_cache = weakref.WeakKeyDictionary()
# This is used to display video to the screen.
self.fullscreen_surface = None
# Info.
self.info = { "renderer" : "sw" }
pygame.display.init()
renpy.display.interface.post_init()
# Scaling?
renpy.display.scale.init()
def set_mode(self, virtual_size, physical_size, fullscreen):
width, height = virtual_size
fsflag = 0
if fullscreen:
fsflag = pygame.FULLSCREEN
# If a window exists of the right size and flags, use it. Otherwise,
# make our own window.
old_window = pygame.display.get_surface()
if ((old_window is not None) and
(old_window.get_size() == (width, height)) and
(old_window.get_flags() & pygame.FULLSCREEN == fsflag)):
self.window = old_window
else:
self.window = renpy.display.pgrender.set_mode(
(width, height),
fsflag,
32)
# Should we redraw the screen from scratch?
self.full_redraw = True
# The surface used to display fullscreen video.
self.fullscreen_surface = renpy.display.scale.real(self.window)
# Reset this on a mode change.
self.mouse_location = None
self.mouse_backing = None
self.mouse_backing_pos = None
self.mouse_info = None
return True
# private
def show_mouse(self, pos, info):
"""
Actually shows the mouse.
"""
self.mouse_location = pos
self.mouse_info = info
mxo, myo, tex = info
mx, my = pos
mw, mh = tex.get_size()
bx = mx - mxo
by = my - myo
self.mouse_backing_pos = (bx, by)
self.mouse_backing = renpy.display.pgrender.surface((mw, mh), False)
self.mouse_backing.blit(self.window, (0, 0), (bx, by, mw, mh))
self.window.blit(tex, (bx, by))
return bx, by, mw, mh
# private
def hide_mouse(self):
"""
Actually hides the mouse.
"""
size = self.mouse_backing.get_size()
self.window.blit(self.mouse_backing, self.mouse_backing_pos)
rv = self.mouse_backing_pos + size
self.mouse_backing = None
self.mouse_backing_pos = None
self.mouse_location = None
return rv
# private
def draw_mouse(self, show_mouse):
"""
This draws the mouse to the screen, if necessary. It uses the
buffer to minimize the amount of the screen that needs to be
drawn, and only redraws if the mouse has actually been moved.
"""
hardware, x, y, tex = renpy.game.interface.get_mouse_info()
if self.mouse_old_visible != hardware:
pygame.mouse.set_visible(hardware)
self.mouse_old_visible = hardware
# The rest of this is for the software mouse.
if self.suppressed_blit:
return [ ]
if not show_mouse:
tex = None
info = (x, y, tex)
pos = pygame.mouse.get_pos()
if (pos == self.mouse_location and tex and info == self.mouse_info):
return [ ]
updates = [ ]
if self.mouse_location:
updates.append(self.hide_mouse())
if tex and pos and renpy.game.interface.focused:
updates.append(self.show_mouse(pos, info))
return updates
def update_mouse(self):
"""
Draws the mouse, and then updates the screen.
"""
updates = self.draw_mouse(True)
if updates:
pygame.display.update(updates)
def mouse_event(self, ev):
x, y = getattr(ev, 'pos', pygame.mouse.get_pos())
return x, y
def get_mouse_pos(self):
return pygame.mouse.get_pos()
def screenshot(self):
"""
Returns a pygame surface containing a screenshot.
"""
return self.window
def should_redraw(self, needs_redraw, first_pass):
"""
Uses the framerate to determine if we can and should redraw.
"""
if not needs_redraw:
return False
framerate = renpy.config.framerate
if framerate is None:
return True
next_frame = self.next_frame
now = pygame.time.get_ticks()
frametime = 1000.0 / framerate
# Handle timer rollover.
if next_frame > now + frametime:
next_frame = now
# It's not yet time for the next frame.
if now < next_frame and not first_pass:
return False
# Otherwise, it is. Schedule the next frame.
# if next_frame + frametime < now:
next_frame = now + frametime
# else:
# next_frame += frametime
self.next_frame = next_frame
return True
def draw_screen(self, surftree, fullscreen_video):
"""
Draws the screen.
"""
if not fullscreen_video:
updates = [ ]
updates.extend(self.draw_mouse(False))
damage = do_draw_screen(surftree, self.full_redraw)
if damage:
updates.extend(damage)
self.full_redraw = False
updates.extend(self.draw_mouse(True))
pygame.display.update(updates)
else:
self.full_redraw = True
renpy.display.render.kill_old_screen()
renpy.display.focus.take_focuses()
self.suppressed_blit = fullscreen_video
def render_to_texture(self, render, alpha):
rv = renpy.display.pgrender.surface((render.width, render.height), alpha)
draw(rv, None, render, 0, 0, False)
return rv
def is_pixel_opaque(self, what, x, y):
if x < 0 or y < 0 or x >= what.width or y >= what.height:
return 0
for (child, xo, yo, focus, main) in what.visible_children:
cx = x - xo
cy = y - yo
if what.forward:
cx, cy = what.forward.transform(cx, cy)
if isinstance(child, renpy.display.render.Render):
if self.is_pixel_opaque(child, x, y):
return True
else:
cw, ch = child.get_size()
if cx >= cw or cy >= ch:
return False
if not child.get_masks()[3] or child.get_at((cx, cy))[3]:
return True
return False
def mutated_surface(self, surf):
"""
Called to indicate that the given surface has changed.
"""
for i in clippers:
i.mutated.add(id(surf))
if surf in rle_cache:
del rle_cache[surf]
def load_texture(self, surf, transient=False):
"""
Creates a texture from the surface. In the software implementation,
the only difference between a texture and a surface is that a texture
is in the RLE cache.
"""
if transient:
return surf
if renpy.game.less_memory:
return surf
if surf not in rle_cache:
rle_surf = renpy.display.pgrender.copy_surface(surf)
rle_surf.set_alpha(255, pygame.RLEACCEL)
self.mutated_surface(rle_surf)
rle_cache[surf] = rle_surf
return surf
def free_memory(self):
"""
Frees up memory.
"""
rle_cache.clear()
def deinit(self):
"""
Called when we're restarted.
"""
renpy.display.render.free_memory()
return
def quit(self):
"""
Shuts down the drawing system.
"""
pygame.display.quit()
return
def event_peek_sleep(self):
"""
Wait a little bit so the CPU doesn't speed up.
"""
time.sleep(.0001)
+139 -268
View File
@@ -49,7 +49,8 @@ text_tags = dict(
)
text_tags[""] = True
def color(s):
"""
This function converts a hexcode into a color/alpha tuple. Leading
@@ -90,6 +91,7 @@ def color(s):
return (r, g, b, a)
class TextStyle(object):
"""
This is used to represent the style of text that will be displayed
@@ -137,10 +139,14 @@ class TextStyle(object):
return rv
def sizes(self, text):
return self.get_width(text), self.f.get_ascent() - self.f.get_descent()
height = max(self.f.get_ascent() - self.f.get_descent(), self.f.get_height())
return self.get_width(text), height
def render(self, text, antialias, color, black_color, use_colors, time, at, expand, use_cache):
if not text:
height = max(self.f.get_ascent() - self.f.get_descent(), self.f.get_height())
return None, (0, height)
if use_colors:
color = self.color or color
@@ -158,7 +164,7 @@ class TextStyle(object):
if isinstance(font, ImageFont):
rv = font.render(text, antialias, color, black_color)
if self.strikethrough:
sw, sh = rv.get_size()
soh = max(sh / 10, 1)
@@ -170,7 +176,7 @@ class TextStyle(object):
surf = font.render(text, antialias, color)
rv = renpy.display.pgrender.copy_surface(surf)
if self.strikethrough:
sw, sh = surf.get_size()
soh = max(sh / 10, 1)
@@ -188,6 +194,7 @@ class TextStyle(object):
def length(self, text):
return len(text)
class WidgetStyle(object):
"""
@@ -618,25 +625,31 @@ class Text(renpy.display.core.Displayable):
A displayable that can format and display text on the screen.
"""
nosave = [ 'laidout', 'laidout_lineheights', 'laidout_linewidths',
'laidout_width', 'laidout_height', 'laidout_start',
'laidout_length', 'laidout_hyperlinks', 'laidout_lines_last',
'width', 'tokens', 'children', 'child_pos']
__version__ = 2
# This can keep around a reference to a Font, which prevents
# us from saving.
nosave = [ 'laidout' ]
__version__ = 3
def after_upgrade(self, version):
if version <= 0:
if version < 1:
self.activated = None
if version <= 1:
if version < 2:
self.slow_done_time = None
if version < 3:
self.ctc = None
self.slow_start = 0
self.slow_end = None
def after_setstate(self):
self.update()
self.laidout = None
self.needs_update = True
def __init__(self, text, slow=None, slow_done=None,
slow_start=0, pause=None, tokenized=False,
style='default', **properties):
style='default', replaces=None, **properties):
"""
@param text: The text that will be displayed on the screen.
@@ -655,13 +668,10 @@ class Text(renpy.display.core.Displayable):
@param tokenized: True if the text is already tokenized.
"""
super(Text, self).__init__(style=style, **properties)
self.text = text
self.pause = pause
self.keep_pausing = False
self.pause_length = None
self.tokenized = tokenized
if slow or slow is None:
@@ -672,6 +682,8 @@ class Text(renpy.display.core.Displayable):
self.slow_param = slow
self.slow_done = slow_done
self.slow_start = slow_start
self.slow_end = None
# The time when slow_done was called.
self.slow_done_time = None
@@ -680,153 +692,92 @@ class Text(renpy.display.core.Displayable):
self.tokens = None
# The duration of each pause, or None if the pause is infinite.
self.pause_lengths = [ ]
# The width we've been laid out for.
self.width = -1
self.update(redraw=False)
# The displayable that was added to us to supporte nestled ctc.
self.ctc = None
if isinstance(replaces, Text):
self.slow = replaces.slow
self.slow_param = replaces.slow_param
self.slow_start = replaces.slow_start
self.slow_end = replaces.slow_end
self.slow_done = replaces.slow_done
self.slow_done_time = replaces.slow_done_time
self.ctc = replaces.ctc
self.needs_update = True
def per_interact(self):
self.update()
def set_ctc(self, ctc):
"""
Sets the nestled CTC indicator of this text.
"""
self.ctc = ctc
self.needs_update = True
renpy.display.render.redraw(self, 0)
def set_text(self, new_text):
"""
Changes the text display by this object to new_text.
"""
self.text = new_text
self.update()
self.needs_update = True
renpy.display.render.redraw(self, 0)
def set_style(self, style):
"""
Changes the style assocated with this object.
"""
self.style = style
self.update()
def update(self, redraw=True, retokenize=True):
"""
This is called after this widget has been updated by
set_text or set_style.
"""
self.laidout = None
self.child_pos = [ ]
if self.text:
text = self.text
else:
text = u" "
def update(self):
"""
This is called to break this displayable up into tokens.
"""
if not self.needs_update:
return True
# Annoyingly, we can't tokenize until styles get built.
if not renpy.style.styles_built:
return
if retokenize:
if not self.tokenized:
self.tokens = input_tokenizer(text, self.style)
else:
self.tokens = self.text
new_tokens = [ ]
fasts = 0
self.no_wait = False # W0201
self.no_wait_once = False # W0201
self.no_wait_done = False # W0201
self.pauses = 0 # W0201
self.pause_lengths = [ ] # W0201
self.needs_update = False
for i in self.tokens[0]:
type, text = i
if type == "tag":
if text == "p":
new_tokens.append(("tag", 'w'))
new_tokens.append(("newline", "\n"))
self.pauses += 1
self.pause_lengths.append(None)
self.laidout = None
self.child_pos = [ ]
continue
if self.tokenized:
self.tokens = self.text
elif text.startswith("p="):
new_tokens.append(("tag", 'w=' + text[2:]))
new_tokens.append(("newline", "\n"))
self.pauses += 1
self.pause_lengths.append(float(text[2:]))
else:
text = self.text
continue
if self.slow_end is not None:
text = text[:self.slow_end]
elif text == "nw":
self.no_wait = True
if not text:
text = " "
elif text == "fast":
self.no_wait = False
fasts += 1
self.pauses = 0
self.pause_lengths = [ ]
elif text == "w":
self.pauses += 1
self.pause_lengths.append(None)
# Exists and is not 0.
if self.slow_start:
text = text[:self.slow_start] + "{_start}" + text[self.slow_start:]
elif text.startswith("w="):
self.pauses += 1
self.pause_lengths.append(float(text[2:]))
new_tokens.append(i)
self.tokens = input_tokenizer(text, self.style)
self.tokens[0] = new_tokens
# Add the CTC indicator.
if self.ctc is not None:
self.tokens.append([ ("widget", self.ctc) ])
if self.pause is not None:
pause = self.pause
new_tokens = [ ]
for i in self.tokens[0]:
new_tokens.append(i)
type, text = i
if type == "tag":
if text == "fast":
fasts -= 1
if text == "nw":
new_tokens.pop()
# If we have a fast to go, then ignore keep_pausing.
if fasts:
continue
if text == "nw":
self.no_wait_once = True
break
elif text == "w":
if pause == 0:
self.keep_pausing |= True
self.pause_length = None
break
else:
pause -= 1
elif text[:2] == "w=":
if pause == 0:
self.keep_pausing |= True
self.pause_length = float(text[2:])
break
else:
pause -= 1
self.tokens[0] = new_tokens
if not self.slow:
self.no_wait = False
self.no_wait_once = False
# Postprocess the tokens list to create widgets, as necessary.
self.children = [ ] # W0201
@@ -835,52 +786,33 @@ class Text(renpy.display.core.Displayable):
for tl in self.tokens:
ntl = [ ]
tliter = iter(tl)
for kind, i in tl:
if kind == "tag":
if i.startswith("image="):
name = i[6:]
for kind, i in tliter:
kind = "widget"
i = renpy.easy.displayable(name)
if kind == "tag" and i.startswith("image="):
m = re.match(r'image=(.*)', i)
if not m:
raise Exception('Image tag %s could not be parsed.' % i)
i = renpy.easy.displayable(m.group(1))
ntl.append(("widget", i))
if kind == "widget":
self.children.append(i)
else:
if kind == "widget":
self.children.append(i)
ntl.append((kind, i))
ntl.append((kind, i))
newtokens.append(ntl)
self.tokens = newtokens
if redraw:
renpy.display.render.redraw(self, 0)
def event(self, ev, x, y, st):
"""
Space, Enter, or Click ends slow, if it's enabled.
"""
if (self.slow_done_time is not None) and (self.pause_length is not None):
if st > (self.slow_done_time + self.pause_length):
return True
else:
renpy.game.interface.timeout((self.slow_done_time + self.pause_length) - st)
if self.slow and self.style.slow_abortable and renpy.display.behavior.map_event(ev, "dismiss"):
self.slow = False
self.call_slow_done(st)
raise renpy.display.core.IgnoreEvent()
if self.no_wait_done:
return False
for child, xo, yo in self.child_pos:
rv = child.event(ev, x - xo, y - yo, st)
@@ -902,14 +834,10 @@ class Text(renpy.display.core.Displayable):
renpy.display.render.redraw(self, 0)
return rv
def visit(self):
if self.tokens is None:
self.update()
self.update()
return self.children
def layout(self, width, time):
"""
@@ -918,12 +846,11 @@ class Text(renpy.display.core.Displayable):
self.laidout_height.
"""
self.update()
if self.laidout and self.width == width:
return
if self.tokens is None:
self.update()
# Set this, so caching works.
self.width = width
@@ -948,13 +875,6 @@ class Text(renpy.display.core.Displayable):
self.laidout_hyperlinks = [ ] # W0201
# if not self.text:
# text = " "
# else:
# text = self.text
# for i in re.split(r'( |\{[^{}]+\}|\{\{|\n)', text):
tokens = [ ]
for l in self.tokens:
tokens.extend(l)
@@ -980,11 +900,15 @@ class Text(renpy.display.core.Displayable):
continue
if i == "w":
if i == "w" or i.startswith("w="):
# Automatically closes.
continue
elif i == "p" or i.startswith("p="):
# Automatically closes.
triples.append(("newline", tsl[-1], "\n"))
continue
elif i == "nw":
# Automatically closes.
continue
@@ -994,18 +918,18 @@ class Text(renpy.display.core.Displayable):
continue
elif i == "fast":
# Automatically closes.
continue
elif i == "_start":
# Automatically closes.
triples.append(("start", tsl[-1], ""))
continue
elif i.startswith("a="):
m = re.match(r'a=(.*)', i)
if not m:
raise Exception('Hyperlink tag %s could not be parsed.' % i)
elif i.startswith("a="):
# TODO: check to see if we need to be focused.
target = m.group(1)
target = i[2:]
hls = renpy.config.hyperlink_styler(target)
old_prefix = hls.prefix
@@ -1077,20 +1001,12 @@ class Text(renpy.display.core.Displayable):
tsl[-1].black_color = style.black_color
tsl[-1].update()
elif i.startswith("font="):
elif i.startswith("font"):
m = re.match(r'font=(.*)', i)
if not m:
raise Exception('Font tag %s could not be parsed.' % i)
tsl[-1].font = m.group(1)
tsl[-1].font = i[5:]
tsl[-1].update()
elif i.startswith("size"):
elif i.startswith("size="):
m = re.match(r'size=(\+|-|)(\d+)', i)
@@ -1105,14 +1021,9 @@ class Text(renpy.display.core.Displayable):
tsl[-1].size = int(m.group(2))
tsl[-1].update()
elif i.startswith("color"):
elif i.startswith("color="):
m = re.match(r'color=(\#?[a-fA-F0-9]+)', i)
if not m:
raise Exception('Color tag %s could not be parsed.' % i)
tsl[-1].color = color(m.group(1))
tsl[-1].color = color(i[6:])
tsl[-1].update()
else:
@@ -1134,7 +1045,6 @@ class Text(renpy.display.core.Displayable):
elif kind == "word":
triples.append(("word", tsl[-1], i))
elif kind == "widget":
pass
@@ -1172,7 +1082,6 @@ class Text(renpy.display.core.Displayable):
if not l:
l.append(('word', tsl[-1], ' '))
justify = self.style.justify
for l in linetriples:
@@ -1209,7 +1118,6 @@ class Text(renpy.display.core.Displayable):
if oldts:
line.append((oldts, cur))
if renpy.config.rtl:
@@ -1248,55 +1156,14 @@ class Text(renpy.display.core.Displayable):
self.laidout_linewidths.append(width)
self.laidout_lineheights.append(height)
self.laidout_width = max(width, self.laidout_width)
self.laidout_height += height + self.style.line_spacing
self.laidout_height += height + max(self.style.line_spacing, 0)
# For the newline.
self.laidout_length += 1
def get_simple_length(self):
def render_pass(self, dest_render, dest_surface, xo, yo, color, black_color, user_colors, length, time, at, child_pos, add_focus, expand):
"""
Returns a simple length of the text in the first segment of
the tokens. Doesn't use the same algorithm as get_laidout_length,
so isn't suitable for slow_start.
"""
rv = 0
for tl in self.tokens:
for type, text in tl:
if type == "newline":
rv += len(text)
elif type == "word":
rv += len(text)
elif type == "space":
rv += len(text)
elif type == "widget":
rv += 1
elif type == "tag" and text == "fast":
rv = 0
return rv
def get_laidout_length(self):
"""
The (reasonably arbitrary) length this text field was laidout
to. This can only be called after the text field was drawn
(that is, after it has been on the screen for an interaction
with the user. Otherwise, it returns sys.maxint.
"""
if not self.laidout:
return sys.maxint
return self.laidout_length
def render_pass(self, r, xo, yo, color, black_color, user_colors, length, time, at, child_pos, add_focus, expand):
"""
Renders the text to r at the offsets. Color is the base color,
Renders the text at the offsets. Color is the base color,
and user_colors controls if the user can override those colors.
Returns True if all characters were rendered, or False if a
@@ -1360,10 +1227,13 @@ class Text(renpy.display.core.Displayable):
actual_y = y + max_ascent - ts.get_ascent()
if surf:
r.blit(surf, (x + xo, actual_y + yo))
if isinstance(surf, renpy.display.render.Render):
dest_render.blit(surf, (x + xo, actual_y + yo))
else:
dest_surface.blit(surf, (x + xo, actual_y + yo))
if add_focus and ts.hyperlink is not None:
r.add_focus(self, ts.hyperlink, x + xo, y + yo, sw, sh)
dest_render.add_focus(self, ts.hyperlink, x + xo, y + yo, sw, sh)
if not isinstance(text, (str, unicode)):
child_pos.append((text, x + xo, actual_y + yo))
@@ -1394,13 +1264,7 @@ class Text(renpy.display.core.Displayable):
self.slow_done = None
self.slow_done_time = st
if self.pause_length:
renpy.game.interface.timeout(self.pause_length)
if self.no_wait_once:
self.no_wait_done = True
renpy.game.interface.timeout(0)
def render(self, width, height, st, at):
if self.slow:
@@ -1450,26 +1314,33 @@ class Text(renpy.display.core.Displayable):
self.layout(width + mindsx - maxdsx, st)
if self.slow and speed:
start = max(self.slow_start, self.laidout_start)
start = self.laidout_start
length = start + int(st * speed)
else:
length = sys.maxint
self.call_slow_done(st)
final_width = self.laidout_width - mindsx + maxdsx + max(self.style.first_indent, self.style.rest_indent)
final_height = self.laidout_height - mindsy + maxdsy
rv = renpy.display.render.Render(self.laidout_width - mindsx + maxdsx, self.laidout_height - mindsy + maxdsy)
rv = renpy.display.render.Render(final_width, final_height)
surf = renpy.display.pgrender.surface((final_width, final_height), True)
for dsxo, dsyo in dslist:
self.render_pass(rv, dsxo - mindsx, dsyo - mindsy, self.style.drop_shadow_color, self.style.drop_shadow_color, False, length, st, at, [ ], False, 0)
self.render_pass(rv, surf, dsxo - mindsx, dsyo - mindsy, self.style.drop_shadow_color, self.style.drop_shadow_color, False, length, st, at, [ ], False, 0)
for expand, color, dsxo, dsyo in outlines:
self.render_pass(rv, dsxo - mindsx - expand, dsyo - mindsy - expand, color, color, False, length, st, at, [ ], False, expand)
self.render_pass(rv, surf, dsxo - mindsx - expand, dsyo - mindsy - expand, color, color, False, length, st, at, [ ], False, expand)
self.child_pos = [ ]
if self.render_pass(rv, -mindsx, -mindsy, self.style.color, self.style.black_color, True, length, st, at, self.child_pos, True, 0):
if self.render_pass(rv, surf, -mindsx, -mindsy, self.style.color, self.style.black_color, True, length, st, at, self.child_pos, True, 0):
if self.slow:
self.call_slow_done(st)
tex = renpy.display.draw.load_texture(surf, transient=True)
rv.blit(tex, (0, 0), index=0)
if self.slow:
renpy.display.render.redraw(self, 0)
@@ -1482,7 +1353,7 @@ class Text(renpy.display.core.Displayable):
if renpy.config.hyperlink_focus:
return renpy.config.hyperlink_focus(self.laidout_hyperlinks[renpy.display.focus.argument])
def unfocus(self):
def unfocus(self, default=False):
self.laidout = None
renpy.display.render.redraw(self, 0)
+199 -261
View File
@@ -19,17 +19,6 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file contains code contributed by Brian Turcotte, the copyright
# assignment follows:
#
# Copyright for nonlinear ramp code added to ImageDissolve is hereby
# assigned to PyTom <pytom@bishoujo.us>.
#
# And feel free to change, improve, fold, spindle, or mutilate it,
# obviously.
#
# Cheers, Brian Turcotte (shaja).
# NOTE:
# Transitions need to be able to work even when old_widget and new_widget
# are None, at least to the point of making it through __init__. This is
@@ -60,6 +49,11 @@ class Transition(renpy.display.core.Displayable):
def visit(self):
return [ self.new_widget, self.old_widget ] # E1101
def per_interact(self):
self.new_widget.per_interact()
self.old_widget.per_interact()
def null_render(d, width, height, st, at):
d.events = True
@@ -109,7 +103,7 @@ class MultipleTransition(Transition):
and the last will be True.
"""
def __init__(self, args, old_widget=None, new_widget=None):
def __init__(self, args, old_widget=None, new_widget=None, **properties):
if len(args) % 2 != 1 or len(args) < 3:
raise Exception("MultipleTransition requires an odd number of arguments, and at least 3 arguments.")
@@ -133,57 +127,54 @@ class MultipleTransition(Transition):
self.transitions.append(trans(old_widget=old, new_widget=new))
super(MultipleTransition, self).__init__(sum([i.delay for i in self.transitions]), **properties)
super(MultipleTransition, self).__init__(sum([i.delay for i in self.transitions]))
self.event_target = None
self.time_offset = 0
self.new_widget = self.transitions[-1]
self.events = False
def visit(self):
return [ i for i in self.screens if isinstance(i, renpy.display.core.Displayable)] + self.transitions
def per_interact(self):
for i in self.visit():
i.per_interact()
def render(self, width, height, st, at):
if renpy.game.less_updates:
return null_render(self, width, height, st, at)
while True:
trans = self.transitions[0]
stoff = st - self.time_offset
for trans in self.transitions[:-1]:
if stoff < trans.delay:
if trans.delay > st:
break
if len(self.transitions) == 1:
break
self.time_offset += trans.delay
self.transitions.pop(0)
st -= trans.delay
if len(self.transitions) == 1:
else:
trans = self.transitions[-1]
self.events = True
self.event_target = trans
surf = renpy.display.render.render(trans, width, height, stoff, at)
surf = renpy.display.render.render(trans, width, height, st, at)
width, height = surf.get_size()
rv = renpy.display.render.Render(width, height)
rv.blit(surf, (0, 0))
if stoff > 0:
renpy.display.render.redraw(self, stoff)
if st < trans.delay:
renpy.display.render.redraw(self, trans.delay - st)
return rv
def Fade(out_time, hold_time, in_time,
old_widget=None, new_widget=None,
def Fade(out_time,
hold_time,
in_time,
old_widget=None,
new_widget=None,
color=None,
widget=None,
alpha=False,
):
"""
@@ -224,12 +215,12 @@ def Fade(out_time, hold_time, in_time,
if not widget:
widget = renpy.display.image.Solid((0, 0, 0, 255))
args = [ False, dissolve(out_time), widget ]
args = [ False, dissolve(out_time, alpha=alpha), widget ]
if hold_time:
args.extend([ notrans(hold_time), widget, ])
args.extend([dissolve(in_time), True ])
args.extend([dissolve(in_time, alpha=alpha), True ])
return MultipleTransition(args, old_widget=old_widget, new_widget=new_widget)
@@ -274,21 +265,14 @@ class Pixellate(Transition):
visible = self.new_widget
self.events = True
rdr = render(visible, width, height, st, at)
surf = rdr.pygame_surface(False)
size = surf.get_size()
newsurf = renpy.display.pgrender.surface(size, surf)
px = 2 ** step
renpy.display.module.pixellate(surf, newsurf, px, px, px, px)
renpy.display.render.mutated_surface(newsurf)
rv = renpy.display.render.Render(rdr.width, rdr.height)
rv.blit(newsurf, (0, 0))
rv.depends_on(rdr)
rv.blit(rdr, (0, 0))
rv.operation = renpy.display.render.PIXELLATE
rv.operation_parameter = 2 ** step
renpy.display.render.redraw(self, 0)
@@ -329,50 +313,25 @@ class Dissolve(Transition):
self.events = True
return render(self.new_widget, width, height, st, at)
if st < self.time:
renpy.display.render.redraw(self, 0)
alpha = min(255, int(255 * st / self.time))
complete = min(1.0, st / self.time)
bottom = render(self.old_widget, width, height, st, at)
top = render(self.new_widget, width, height, st, at)
bottom_surface = bottom.pygame_surface(self.alpha)
top_surface = top.pygame_surface(self.alpha)
width = min(top.width, bottom.width)
height = min(top.height, bottom.height)
def draw(dest, x, y):
dw, dh = dest.get_size()
rv = renpy.display.render.Render(width, height, opaque=not self.alpha)
w = min(dw, width + x)
h = min(dh, height + y)
rv.operation = renpy.display.render.DISSOLVE
rv.operation_alpha = self.alpha
rv.operation_complete = complete
rv.blit(bottom, (0, 0), focus=False, main=False)
rv.blit(top, (0, 0), focus=True, main=True)
if w <= 0 or h <= 0:
return
renpy.display.render.redraw(self, 0)
renpy.display.module.blend(
bottom_surface.subsurface((-x, -y, w, h)),
top_surface.subsurface((-x, -y, w, h)),
dest.subsurface((0, 0, w, h)),
alpha)
if self.alpha:
surf = renpy.display.pgrender.surface((width, height), True)
draw(surf, 0, 0)
renpy.display.render.mutated_surface(surf)
rv = renpy.display.render.Render(width, height)
rv.blit(surf, (0, 0))
else:
rv = renpy.display.render.Render(width, height, draw_func=draw, opaque=True)
rv.depends_on(top, True)
rv.depends_on(bottom)
return rv
@@ -380,38 +339,6 @@ class ImageDissolve(Transition):
"""
This dissolves the old scene into the new scene, using an image
to control the dissolve process.
A list of values is used to control this mapping. This list of
values consists 256 fully transparent values, a ramp (of a
specified number of steps) from full transparency to full opacity,
and 256 fully opaque values. A 256 entry window is slid over this
list, and the values found within are used to map the red channel
of the image onto the opacity of the new scene.
Basically, this means that while pixels come in first, black last,
and the ramp controls the sharpness of the transition.
@param image: The image that will be used to control this
transition. The image should be the same size as the scene being
dissolved.
@param time: The amount of time the dissolve will take.
@param ramplen: The number of pixels of ramp to use. This defaults
to 8.
@param ramptype: Type of alpha ramp. Possible types are: linear, cube,
dcube, mcube. Default is linear. Non-linear types must have
ramplen >= 8. "cube": Ease in, sharp out. "dcube": Sharp in, sharp out.
"mcube": Ease in, ease out.
@param ramp: If given, this is expected to be a sequence of
integers in the range 0 to 255. This sequence explicitly gives the
ramp to be used. If given, this overrides ramplen and ramptype.
@param reverse: This reverses the ramp and the direction of the window
slide. When True, black pixels dissolve in first, and while pixels come
in last.
"""
__version__ = 1
@@ -420,173 +347,175 @@ class ImageDissolve(Transition):
if version < 1:
self.alpha = False
def generate_ramp(self, ramplen, ramptype, explicit_ramp, reverse):
"""
Precomputes the ramp.
"""
def __init__(
self,
image,
time,
ramplen=8,
ramptype='linear',
ramp=None,
reverse=False,
alpha=False,
old_widget=None,
new_widget=None,
**properties):
ramp = '\x00' * 256
if explicit_ramp is not None:
for i in explicit_ramp:
ramp += chr(i)
else:
if ramptype == 'cube':
# make sure ramplen is big enough, to avoid div-by-0 errors
# Not much point in nonlinear if the size is that small, anyway
if ramplen >= 8:
table = []
for i in range(ramplen):
table.append(i * i * i)
scale = max(table) / 255.0
for i in range(ramplen):
#print i, table[i], table[i] / scale
ramp += chr(int(table[i] / scale))
else:
ramptype = 'linear'
elif ramptype == 'dcube':
if ramplen >= 8:
table = []
for i in range(ramplen / 2 - ramplen, ramplen / 2):
table.append(i * i * i)
adj = abs(min(table))
for i in range(len(table)):
table[i] += adj
scale = max(table) / 255.0
#print "scale:", scale
for i in range(ramplen):
#print i, table[i], table[i] / scale
ramp += chr(int(table[i] / scale))
else:
ramptype = 'linear'
elif ramptype == 'mcube':
if ramplen >= 8:
ramplen = (ramplen / 2) * 2 # make sure it's even
table = []
for i in range(ramplen / 2):
table.append(i * i * i)
adj = table[-1]
tmptable = []
for i in table:
tmptable.append(i)
for i in range(1, len(table) + 1):
tmptable.append(abs(table[len(table) - i] - adj) + adj)
table = tmptable
scale = max(table) / 255.0
#print "scale:", scale
for i in range(ramplen):
#print i, table[i], table[i] / scale
ramp += chr(int(table[i] / scale))
else:
ramptype = 'linear'
if ramptype == 'linear':
for i in range(ramplen):
ramp += chr(255 * i / ramplen)
ramp += '\xff' * 256
if reverse:
ramp = list(ramp)
ramp.reverse()
ramp = ''.join(ramp)
return ramp
# ramptype and ramp are now unused, but are kept for compatbility with
# older code.
def __init__(self, image, time, ramplen=8, ramptype='linear', ramp=None, reverse=False, alpha=False,
old_widget=None, new_widget=None, **properties):
super(ImageDissolve, self).__init__(time, **properties)
self.time = time
self.old_widget = old_widget
self.new_widget = new_widget
self.events = False
self.alpha = alpha
self.image = renpy.display.im.image(image)
if not reverse:
# Copies red -> alpha
matrix = renpy.display.im.matrix(
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
1, 0, 0, 0, 0)
else:
# Copies 1-red -> alpha
matrix = renpy.display.im.matrix(
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
-1, 0, 0, 0, 1)
self.image = renpy.display.im.MatrixColor(image, matrix)
if ramp is not None:
ramplen = len(ramp)
self.ramp = self.generate_ramp(ramplen, ramptype, ramp, reverse)
self.steps = ramplen + 256
self.reverse = reverse
# The length of the ramp.
self.ramplen = max(ramplen, 1)
def visit(self):
return super(ImageDissolve, self).visit() + [ self.image ]
def render(self, width, height, st, at):
if renpy.game.less_updates:
return null_render(self, width, height, st, at)
if st >= self.time:
if st >= self.delay:
self.events = True
return render(self.new_widget, width, height, st, at)
image = renpy.display.im.cache.get(self.image)
image = render(self.image, width, height, st, at)
bottom = render(self.old_widget, width, height, st, at)
top = render(self.new_widget, width, height, st, at)
if st < self.time:
renpy.display.render.redraw(self, 0)
width = min(bottom.width, top.width, image.width)
height = min(bottom.height, top.height, image.height)
step = int(self.steps * st / self.time)
rv = renpy.display.render.Render(width, height, opaque=not self.alpha)
if self.reverse:
step = self.steps - step
rv.operation = renpy.display.render.IMAGEDISSOLVE
rv.operation_alpha = self.alpha
rv.operation_complete = st / self.delay
rv.operation_parameter = self.ramplen
ramp = self.ramp[step:step+256]
rv.blit(image, (0, 0), focus=False, main=False)
rv.blit(bottom, (0, 0), focus=False, main=False)
rv.blit(top, (0, 0), focus=True, main=True)
renpy.display.render.redraw(self, 0)
return rv
class AlphaDissolve(Transition):
"""
:doc: other
:args: (control, delay=0.0, alpha=False, reverse=False)
This transition uses a control displayable (almost always some
sort of animated transform) to transition from one screen to
another. The transform is evaluated. The new screen is used where
the transform is opaque, and the old image is used when it is
transparent.
`control`
The control transform.
`delay`
The time the transition takes, before ending.
`alpha`
If true, the image is composited with what's behind it. If false,
the default, the image is opaque and overwrites what's behind it.
`reverse`
If true, the alpha channel is reversed. Opaque areas are taken
from the old image, while transparent areas are taken from the
new image.
"""
def __init__(
self,
control,
delay=0.0,
old_widget=None,
new_widget=None,
alpha=False,
reverse=False,
**properties):
super(AlphaDissolve, self).__init__(delay, **properties)
self.control = renpy.display.layout.Fixed()
self.control.add(control)
self.old_widget = renpy.easy.displayable(old_widget)
self.new_widget = renpy.easy.displayable(new_widget)
self.events = False
self.alpha = alpha
self.reverse = reverse
def visit(self):
return super(AlphaDissolve, self).visit() + [ self.control ]
def render(self, width, height, st, at):
if st >= self.delay:
self.events = True
bottom = render(self.old_widget, width, height, st, at)
top = render(self.new_widget, width, height, st, at)
bottom_surface = bottom.pygame_surface(self.alpha)
top_surface = top.pygame_surface(self.alpha)
iw, ih = image.get_size()
width = min(bottom.width, top.width)
height = min(bottom.height, top.height)
width = min(bottom.width, top.width, iw)
height = min(bottom.height, top.height, ih)
def draw(dest, x, y):
control = render(self.control, width, height, st, at)
dw, dh = dest.get_size()
rv = renpy.display.render.Render(width, height, opaque=not self.alpha)
w = min(dw, width + x)
h = min(dh, height + y)
rv.operation = renpy.display.render.IMAGEDISSOLVE
rv.operation_alpha = self.alpha
rv.operation_complete = 256.0 / (256.0 + 256.0)
rv.operation_parameter = 256.0
renpy.display.module.imageblend(
bottom_surface.subsurface((-x, -y, w, h)),
top_surface.subsurface((-x, -y, w, h)),
dest.subsurface((0, 0, w, h)),
image.subsurface((-x, -y, w, h)),
ramp)
if self.alpha:
surf = renpy.display.pgrender.surface((width, height), True)
draw(surf, 0, 0)
renpy.display.render.mutated_surface(surf)
rv = renpy.display.render.Render(width, height)
rv.blit(surf, (0, 0))
rv.blit(control, (0, 0), focus=False, main=False)
if not self.reverse:
rv.blit(bottom, (0, 0), focus=False, main=False)
rv.blit(top, (0, 0), focus=True, main=True)
else:
rv = renpy.display.render.Render(width, height, draw_func=draw, opaque=True)
rv.blit(top, (0, 0), focus=True, main=True)
rv.blit(bottom, (0, 0), focus=False, main=False)
rv.depends_on(top, True)
rv.depends_on(bottom)
return rv
class CropMove(Transition):
"""
@@ -842,6 +771,16 @@ def position(d):
return xpos, ypos, xanchor, yanchor
def offsets(d):
xpos, ypos, xanchor, yanchor, xoffset, yoffset, subpixel = d.get_placement()
if renpy.config.movetransition_respects_offsets:
return { 'xoffset' : xoffset, 'yoffset' : yoffset }
else:
return { }
# These are used by MoveTransition.
def MoveFactory(pos1, pos2, delay, d, **kwargs):
if pos1 == pos2:
@@ -849,10 +788,10 @@ def MoveFactory(pos1, pos2, delay, d, **kwargs):
return renpy.display.motion.Move(pos1, pos2, delay, d, **kwargs)
def default_enter_factory(pos, delay, d):
def default_enter_factory(pos, delay, d, **kwargs):
return d
def default_leave_factory(pos, delay, d):
def default_leave_factory(pos, delay, d, **kwargs):
return None
# These can be used to move things in and out of the screen.
@@ -936,13 +875,17 @@ def MoveTransition(delay, old_widget=None, new_widget=None, factory=None, enter
else:
child = new
if position(old) != position(new):
return factory(position(old),
position(new),
old_pos = position(old)
new_pos = position(new)
if old_pos != new_pos:
return factory(old_pos,
new_pos,
delay,
child,
**offsets(child)
)
else:
return child
@@ -976,19 +919,16 @@ def MoveTransition(delay, old_widget=None, new_widget=None, factory=None, enter
# Wraps the displayable found in SLE so that the various timebases
# are maintained.
def wrap(sle):
key, zorder, st, at, d = sle
return renpy.display.layout.AdjustTimes(d, st, at)
return renpy.display.layout.AdjustTimes(sle.displayable, sle.show_time, sle.animation_time)
def tag(sle):
if sle[0] is None:
tag = sle[4]
else:
tag = sle[0]
return tag
return sle.tag or sle.displayable
def merge(sle, d):
return (sle[0], sle[1], 0, sle[3], d)
rv = sle.copy()
rv.show_time = 0
rv.displayable = d
return rv
# A list of tags on the new layer.
new_tags = set()
@@ -1012,7 +952,7 @@ def MoveTransition(delay, old_widget=None, new_widget=None, factory=None, enter
# In old, not in new.
if old_tag not in new_tags:
move = leave_factory(position(old_d), delay, old_d)
move = leave_factory(position(old_d), delay, old_d, **offsets(old_d))
if move is None:
continue
@@ -1032,7 +972,7 @@ def MoveTransition(delay, old_widget=None, new_widget=None, factory=None, enter
if new_tag == old_tag:
break
move = enter_factory(position(new_d), delay, new_d)
move = enter_factory(position(new_d), delay, new_d, **offsets(old_d))
if move is None:
continue
@@ -1047,7 +987,7 @@ def MoveTransition(delay, old_widget=None, new_widget=None, factory=None, enter
else:
child = new_d
move = factory(position(old_d), position(new_d), delay, child)
move = factory(position(old_d), position(new_d), delay, child, **offsets(child))
if move is None:
continue
@@ -1060,7 +1000,7 @@ def MoveTransition(delay, old_widget=None, new_widget=None, factory=None, enter
new_tag = tag(new_sle)
new_d = wrap(new_sle)
move = enter_factory(position(new_d), delay, new_d)
move = enter_factory(position(new_d), delay, new_d, **offsets(new_d))
if move is None:
continue
@@ -1082,8 +1022,6 @@ def MoveTransition(delay, old_widget=None, new_widget=None, factory=None, enter
return rv
def ComposeTransition(trans, before=None, after=None, new_widget=None, old_widget=None):
if before is not None:
old = before(new_widget=new_widget, old_widget=old_widget)

Some files were not shown because too many files have changed in this diff Show More